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

Angular记录(9)

启用 HTTP 服务

Angular记录(9)

模拟数据服务器

Angular记录(9)

Angular记录(9)

Angular记录(9)

Angular记录(9)

英雄与 HTTP

Angular记录(9)

通过 HttpClient 获取英雄

Angular记录(9)

Http 方法返回单个值

Angular记录(9)

HttpClient.get 返回响应数据

Angular记录(9)

错误处理

Angular记录(9)

Angular记录(9)

窥探 Observable

Angular记录(9)

通过 id 获取英雄

Angular记录(9)

修改英雄

Angular记录(9)

Angular记录(9)

添加新英雄

Angular记录(9)

Angular记录(9)

删除某个英雄

Angular记录(9)

Angular记录(9)

根据名字搜索

Angular记录(9)

为仪表盘添加搜索功能

Angular记录(9)

创建 HeroSearchComponen

Angular记录(9)

修正 HeroSearchComponent 类,RxJS Subject 类型的 searchTerms

Angular记录(9)

串联 RxJS 操作符

Angular记录(9)

最终代码

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记录(9)

Angular记录(9)

Angular记录(9)

Angular记录(9)

Angular记录(9)

上一篇:Angular记录(8)


下一篇:Angular记录(7)