Angular记录(9)
文档资料
- 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions
箭头函数--ES6文档:http://es6.ruanyifeng.com/#docs/function#箭头函数
- Promise 对象--JS教程:https://wangdoc.com/javascript/async/promise.html
- Promise--ES6文档:http://es6.ruanyifeng.com/#docs/promise
- Promise--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise
Promise.prototype.then()--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/then
- 教程:英雄指南:https://www.angular.cn/tutorial#tutorial-tour-of-heroes
- 工作区与项目文件的结构:https://www.angular.cn/guide/file-structure
- 组件简介:https://www.angular.cn/guide/architecture-components
CLI 命令参考手册:https://www.angular.cn/cli
HTTP
HTTP:https://www.angular.cn/tutorial/toh-pt6#http

启用 HTTP 服务

模拟数据服务器




英雄与 HTTP

通过 HttpClient 获取英雄

Http 方法返回单个值

HttpClient.get 返回响应数据

错误处理


窥探 Observable

通过 id 获取英雄

修改英雄


添加新英雄


删除某个英雄


根据名字搜索

为仪表盘添加搜索功能

创建 HeroSearchComponen

修正 HeroSearchComponent 类,RxJS Subject 类型的 searchTerms

串联 RxJS 操作符

最终代码
hero.service.ts的代码
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
import { Hero } from './hero';
import { MessageService } from './message.service';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({ providedIn: 'root' })
export class HeroService {
private heroesUrl = 'api/heroes'; // URL to web api
constructor(
private http: HttpClient,
private messageService: MessageService) { }
/** GET heroes from the server */
getHeroes (): Observable<Hero[]> {
return this.http.get<Hero[]>(this.heroesUrl)
.pipe(
tap(_ => this.log('fetched heroes')),
catchError(this.handleError<Hero[]>('getHeroes', []))
);
}
/** GET hero by id. Return `undefined` when id not found */
getHeroNo404<Data>(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/?id=${id}`;
return this.http.get<Hero[]>(url)
.pipe(
map(heroes => heroes[0]), // returns a {0|1} element array
tap(h => {
const outcome = h ? `fetched` : `did not find`;
this.log(`${outcome} hero id=${id}`);
}),
catchError(this.handleError<Hero>(`getHero id=${id}`))
);
}
/** GET hero by id. Will 404 if id not found */
getHero(id: number): Observable<Hero> {
const url = `${this.heroesUrl}/${id}`;
return this.http.get<Hero>(url).pipe(
tap(_ => this.log(`fetched hero id=${id}`)),
catchError(this.handleError<Hero>(`getHero id=${id}`))
);
}
/* GET heroes whose name contains search term */
searchHeroes(term: string): Observable<Hero[]> {
if (!term.trim()) {
// if not search term, return empty hero array.
return of([]);
}
return this.http.get<Hero[]>(`${this.heroesUrl}/?name=${term}`).pipe(
tap(_ => this.log(`found heroes matching "${term}"`)),
catchError(this.handleError<Hero[]>('searchHeroes', []))
);
}
//////// Save methods //////////
/** POST: add a new hero to the server */
addHero (hero: Hero): Observable<Hero> {
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
tap((newHero: Hero) => this.log(`added hero w/ id=${newHero.id}`)),
catchError(this.handleError<Hero>('addHero'))
);
}
/** DELETE: delete the hero from the server */
deleteHero (hero: Hero | number): Observable<Hero> {
const id = typeof hero === 'number' ? hero : hero.id;
const url = `${this.heroesUrl}/${id}`;
return this.http.delete<Hero>(url, httpOptions).pipe(
tap(_ => this.log(`deleted hero id=${id}`)),
catchError(this.handleError<Hero>('deleteHero'))
);
}
/** PUT: update the hero on the server */
updateHero (hero: Hero): Observable<any> {
return this.http.put(this.heroesUrl, hero, httpOptions).pipe(
tap(_ => this.log(`updated hero id=${hero.id}`)),
catchError(this.handleError<any>('updateHero'))
);
}
/**
* Handle Http operation that failed.
* Let the app continue.
* @param operation - name of the operation that failed
* @param result - optional value to return as the observable result
*/
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
/** Log a HeroService message with the MessageService */
private log(message: string) {
this.messageService.add(`HeroService: ${message}`);
}
}
代码理解:hero.service.ts






Angular记录(9)的更多相关文章
- Angular记录(2)
文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...
- Angular记录(11)
开始使用Angular写页面 使用WebStorm:版本2018.3.5 官网资料 资料大部分有中文翻译,很不错 速查表:https://www.angular.cn/guide/cheatsheet ...
- Angular记录(10)
文档资料 速查表:https://www.angular.cn/guide/cheatsheet 风格指南:https://www.angular.cn/guide/styleguide Angula ...
- Angular记录(8)
文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...
- Angular记录(7)
文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...
- Angular记录(6)
文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...
- Angular记录(5)
文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...
- Angular记录(4)
文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...
- Angular记录(3)
文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...
随机推荐
- 阿里云安装MySQL5.7
长话短说: step1:下载mysql源安装包:wget http://dev.mysql.com/get/mysql57-community-release-el7-8.noarch.rpm ste ...
- SQLServer删除登录帐户
删除登陆账户注意事项 不能删除正在登录的登录名. 也不能删除拥有任何安全对象.服务器级对象或 SQL Server 代理作业的登录名. 可以删除数据库用户映射到的登录名,但是这会创建孤立用户. 有关详 ...
- Java基础系列--06_抽象类与接口概述
抽象类 (1)如果多个类中存在相同的方法声明,而方法体不一样,我们就可以只提取方法声明. 如果一个方法只有方法声明,没有方法体,那么这个方法必须用抽象修饰. 而一个类中如果有抽象方法,这个类必须定义为 ...
- 关于SSH的那些事
SSH: Secure Shell Protocol (安全外壳协议) Secure Shell,又可记为安全外壳协议(SSH) Secure Shell,又可记为安全外壳协议(SSH),最初是UN ...
- MongoDB系列:三、springboot整合mongoDB的简单demo
在上篇 MongoDB常用操作练习 中,我们在命令提示符窗口使用简单的mongdb的方法操作数据库,实现增删改查及其他的功能.在本篇中,我们将mongodb与spring boot进行整合,也就是在j ...
- [官网]Windows modules
Windows modules https://docs.ansible.com/ansible/latest/modules/list_of_windows_modules.html win_acl ...
- Django(五)母版继承、Cookie、视图装饰器等
大纲 一.内容回顾 补充:默认值 补充:命名空间 二.模板语言 1.母版继承 2.include 3.自定义simple_tag 三.Cookie Cookie 使用总结 四.视图 1.获取用户请求相 ...
- vue-cli3相关
此时做的一个vue-cli3项目build后,app.js达到了10M,主要为elementui.quill等组件: 最开始使用“compression-webpack-plugin”插件根据网上的说 ...
- Linux(Ubuntu)使用日记------为程序添加桌面快捷方式
我们Ubuntu中的所以的程序的快捷方式都放在了/usr/share/applications文件夹下,都是以.desktop结尾的文件.我们可以在这个文件夹下创建我们的快捷方式,然后复制到桌面即可 ...
- Vue.js 2.x笔记:状态管理Vuex(7)
1. Vuex简介与安装 1.1 Vuex简介 Vuex是为vue.js应用程序开发的状态管理模式,解决的问题: ◊ 组件之间的传参,多层嵌套组件之间的传参以及各组件之间耦合度过高问题 ◊ 不同状态中 ...