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 ...
随机推荐
- Hive动态分区
1.开启支持动态分区 set hive.exec.dynamic.partition=true; --默认为false set hive.exec.dynamic.partition.mode=nos ...
- javafx--tableView笔记-----tableView里已经填充了实体类数据但是很狗血地显示不出来
private String cClass private String cUp private String cDown 刚开始实体类的字段 cClassCol.setCellValueFactor ...
- python使用rabbitMQ介绍二(工作队列模式)
一模式介绍 第一章节的生产-消费者模式,是非常简单的模式,一发一收.在实际的应用中,消费者有的时候需要工作较长的时间,则需要增加消费者. 队列模型: 这时mq实现了一下几个功能: rabbitmq循环 ...
- SQLServer之删除用户定义的数据库角色
删除用户定义的数据库角色注意事项 无法从数据库删除拥有安全对象的角色. 若要删除拥有安全对象的数据库角色,必须首先转移这些安全对象的所有权,或从数据库删除它们. 无法从数据库删除拥有成员的角色. 若要 ...
- 吴军武志红万维刚薛兆丰何帆曾鸣李笑来罗永浩等得到APP专栏作者的书3
整理了一下最近两三年内看过的得到APP专栏与课程作者的得到精选文集和他们写过的书共本.新增吴军1本,武志红1本. 其中:武志红3本,熊太行1本,薛兆丰2本,吴军4本,何帆3本,曾鸣2本,万维刚1本,李 ...
- AI和机器学习对云应用的安全产生了何种影响?
AI和机器学习对云应用的安全产生了何种影响? 正如其他许多新兴技术一样,AI是一把双刃剑,它对于云计算的安全影响是双重的:这项技术可以使工作负载变得更加安全,但也可能会为新的威胁打开大门. 出现这种分 ...
- Linux新手随手笔记
RPM通过将安装规则与源代码打包到一起,来降低软件的安装难度 yum 通过将大量的常用RPM软件存放在一起,解决软件包之间的依赖关系,进一步降低软件的安装难度 rhel 5\6 init rhel 7 ...
- Unity3D介绍
Unity3D介绍:Unity3D是一个游戏开发引擎 由Unity Technologies开发的一个让玩家轻松创建诸如三维视频游戏.建筑可视化.实时三维动画等类型互动内容的多平台的综合型游戏开发工具 ...
- ASP.NET Core 2.1 : 十五.图解路由(2.1 or earler)
本文通过一张图来看一下路由的配置以及请求处理的机制.(ASP.NET Core 系列目录) 一.概述 路由主要有两个主要功能: 将请求的URL与已定义的路由进行匹配,找到该URL对应的处理程序并传入该 ...
- 分布式存储ceph——(1)部署ceph
前言: 很多朋友想学ceph,但是开始ceph部署就让初学者举步为艰,ceph部署时由于国外源的问题(具体大家应该懂得),下载和安装软件便会卡住,停止不前.即使配置搭建了国内源后,执行ceph-dep ...