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 ...
随机推荐
- OpenGL Windows 窗口程序环境搭建
OpenGL环境搭建步骤: Downloading OpenGL 根据官网的说法: In all three major desktop platforms (Linux, macOS, and Wi ...
- 线上centos6出现软死锁 kernel:BUG: soft lockup
线上centos6出现软死锁 kernel:BUG: soft lockup 今天线上一台centos6机器用xshell一直连接不上,然后在xshell上显示 Message from syslog ...
- Activi相关表归纳
Activi相关归纳总结记录: ACT_RE_* : 'RE'表示repository.这个前缀的表包含了流程定义和流程静态资源(图片,规则,等等). ACT_RU_* : 'RU'表示 ...
- VSC 解决红底线问题
话不多说 设置里代码奉上 { "editor.minimap.enabled": false, "workbench.iconTheme": "vs ...
- 我用Python爬取了李沧最近一年多的二手房成交数据得出以下结论
前言 去年年底,博主有购房的意愿,本来是打算在青岛市北购房,怎奈工作变动,意向转移到了李沧,坐等了半年以后,最终选择在红岛附近购置了期房. 也许一些知道青岛红岛的小伙伴会问我,为什么会跑到那鸟不拉屎的 ...
- Python--day06(深浅拷贝、元组、字典、集合)
1. 深浅拷贝 1.1 值拷贝 s1直接将ls中存放的地址拿过来s1内部的值发生任何变化,s2都会随之变化 s1 = ['1','2','3','a']s2 = s1print(id(s1),id ...
- Riemann流形上的梯度,散度与Laplace算子
今天(准确地说是昨天)被学物理的同学问到Stokes定理,想起来我还有一个知道但没有细看的东西,下面整理成提示完整的习题记录一下. 这部分内容将会加进几何学观止,敬请期待.目前正在纂写代数几何簇的部分 ...
- centos6.8 搭建postfix/dovecot邮件服务器
postfix/dovecot邮件服务器 安装配置参考链接 http://www.cnblogs.com/jkklearn/p/7280045.html (domain 为自己域名 xxx.com) ...
- 【c的文件操作】文本文件和二进制文件(内存映像)的不同 文件结尾判断feof , EOF
查看 stdio.h 可以看到如下定义: #define EOF (-1) #define _IOEOF 0x0010 #define feof(_stream) ((_stream)- ...
- java返回数据工具类
import com.qbskj.project.util.SpringUtils; /** * 消息 * */ public class Message { /** * 类型 */ public e ...