文档资料

  • 箭头函数--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)的更多相关文章

  1. Angular记录(2)

    文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...

  2. Angular记录(11)

    开始使用Angular写页面 使用WebStorm:版本2018.3.5 官网资料 资料大部分有中文翻译,很不错 速查表:https://www.angular.cn/guide/cheatsheet ...

  3. Angular记录(10)

    文档资料 速查表:https://www.angular.cn/guide/cheatsheet 风格指南:https://www.angular.cn/guide/styleguide Angula ...

  4. Angular记录(8)

    文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...

  5. Angular记录(7)

    文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...

  6. Angular记录(6)

    文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...

  7. Angular记录(5)

    文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...

  8. Angular记录(4)

    文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...

  9. Angular记录(3)

    文档资料 箭头函数--MDN:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_fun ...

随机推荐

  1. python之控制流

    https://www.cnblogs.com/evablogs/p/6691776.html 条件判断 简单if语句 1 2 3 4 5 >>>name='lily' >&g ...

  2. Linux运维跳槽必备的40道面试精华题(转)

    Linux运维跳槽必备的40道面试精华题(转)   下面是一名资深Linux运维求职数十家公司总结的Linux运维面试精华,助力大家年后跳槽找个高薪好工作. 1.什么是运维?什么是游戏运维? 1)运维 ...

  3. 把ESXi中的虚拟机通过OVA/OVF导出的方式迁移到Proxmox 5

    引用地址:https://blog.csdn.net/zebra2011/article/details/83046841 一.前言    之前发现ESXi是免费的时候,非常兴奋地把几台服务器都装上了 ...

  4. 如莲开发平台(MIS基础框架、Java技术、B/S结构)

    关于     「如莲」是一套MIS类系统基础框架,主要用于各类“管理信息系统”的开发,也适合做网站后台开发.可省去开发时的框架搭建.规范约定.权限管理等基础工作,直接专注于业务功能实现.     「如 ...

  5. Exception in thread "main" org.I0Itec.zkclient.exception.ZkAuthFailedException: Authentication failure is thrown while creating kafka topic

    Exception in thread "main" org.I0Itec.zkclient.exception.ZkAuthFailedException: Authentica ...

  6. windows下mysql 5.7以上版本安装及遇到的问题

    (原) 早些前用window安装mysql挺简单的,一个安装程序,一路下一步. 2006的5.0版本,确实太早了点. 于是官网上又下了一个版本,windows也是提供了二个版本Installer(安装 ...

  7. ProxyChains 的坑, 需要关闭 sip

    之前 10.12.6 还可以的,现在升级下系统就用不了了. search下发生时sip问题. 解决方案就时要关闭这个东西; 关闭SIP reboot # 按住 option 键 # 到系统选择页面后, ...

  8. python rpyc 报错: AttributeError: cannot access 'new'

    Error msg: Traceback (most recent call last): File "/home/hpcm/Desktop/test/install/client.py&q ...

  9. django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named 'MySQLdb'. Did you install mysqlclient or MySQL-python?

    Error msg: Unhandled exception in thread started by <function check_errors.<locals>.wrapper ...

  10. Linux C启动时创建pid文件

    程序在启动时将pid写入文件,当程序再次启动时会进行检测,避免启动多个实例. util-pidfile.h文件 #ifndef __UTIL_PID_H__ #define __UTIL_PID_H_ ...