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 ...
随机推荐
- 记一次 c 语言 的 多线程查找 简单实现
//仅供参考学习 1 #define _CRT_SECURE_NO_WARNINGS //屏蔽 vs 的a #include <stdio.h> #include <stdlib.h ...
- 想知道谁是你的最佳用户?基于Redis实现排行榜周期榜与最近N期榜
本文由云+社区发表 前言 业务已基于Redis实现了一个高可用的排行榜服务,长期以来相安无事.有一天,产品说:我要一个按周排名的排行榜,以反映本周内用户的活跃情况.于是周榜(按周重置更新的榜单)诞生了 ...
- 零代码第一步,做个添加数据的服务先。node.js + mysql
node.js + mysql 实现数据添加的功能.万事基于服务! 增删改查之添加数据. 优点:只需要设置一个json文件,就可以实现基本的添加功能,可以视为是零代码. 添加数据的服务实现的功能: 1 ...
- jQuery的一些简单基础知识
### 什么是jQuery?jQuery(js+Query)是一款优秀的JavaScript库,帮助开发人员用最少的代码做更多的事情,官网网站http://jquery.com/ ### 为什么学习j ...
- Neutron vxlan network
OpenStack 还支持 vxlan 和 gre 这两种 overlay network. overlay network 是指建立在其他网络上的网络. 该网络中的节点可以看作通过虚拟(或逻辑) ...
- Photoshop调出田园照片唯美手绘油画效果
先看看效果图 原片分析:妹子脸上的光不够通透,有些灰暗,整体色调不够分明. 后期思路:色彩往油画风格调整,让画面色彩更加油润.丰富. 基础调整 (1)曝光根据照片的实际情况进行调整 (2)增加阴影部分 ...
- pycharm 安装dilb模块
- mybatis中常见的问题总结
如下所有举例基于springboot+mybatis项目中,SSH使用mybatis的写法也一样,只是形式不同而已 问题1.org.apache.ibatis.binding.BindingExcep ...
- 第一章 初识 MyBatis
概念:优秀持久层框架:实体类和SQL语句之间建立映射关系 与hibernate区别 :自动生成sql语句,并且建立实体类和数据表的映射. MyBatis基本要素:核心对象 核心配置文件 S ...
- 牛客网:将两个单调递增的链表合并为一个单调递增的链表-Python实现-两种方法讲解
方法一和方法二的执行效率,可以大致的计算时间复杂度加以对比,方法一优于方法二 1. 方法一: 思路: 1. 新创建一个链表节点头,假设这里就叫 head3: 2. 因为另外两个链表都为单调递增,所 ...