Angular(15) - 从服务端获取数据 - 官方教程英雄指南之服务调用HTTP数据 (详细解说)

1 从服务中调用HTTP数据, 导入服务

src/app/hero.service.ts
  • 1.1 导入相关服务
import { HttpClient, HttpHeaders } from '@angular/common/http';
  • 1.2 构造函数注入
constructor(
  private http: HttpClient,
  private messageService: MessageService) { }
  • 1.3 保留Message方法,便于提供消息
/** Log a HeroService message with the MessageService */
private log(message: string) {
  this.messageService.add(`HeroService: ${message}`);
}
  • 1.4 定义URL格式
private heroesUrl = 'api/heroes';  // URL to web api

2 通过 HttpClient 获取英雄, 实际上只是将返回的方法修改成从 this.http.get<Hero[]>(this.heroesUrl), 通过模拟的api请求数据

src/app/hero.service.ts
/** GET heroes from the server */
getHeroes(): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
}

3 错误处理

src/app/hero.service.ts
  • 3.1 导入错误类
import { catchError, map, tap } from 'rxjs/operators';
  • 3.2 使用RXJS的结果管道 pipe() 方法来扩展 Observable 的结果,并给它一个 catchError() 操作符, 意思是当执行完成时管道启动, 如果有错误时将会调用错误处理的方法
getHeroes(): Observable<Hero[]> {
  return this.http.get<Hero[]>(this.heroesUrl)
    .pipe(
      catchError(this.handleError<Hero[]>('getHeroes', []))
    );
}
  • 3.3 提供详细方法并将错误的日志输出
/**
 * 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);
  };
}
  • 3.4 监听获取数据事件, 通过RXJS的 tap操作符, 该操作符会查看 Observable 中的值,使用那些值做一些事情,并且把它们传出来。 这种 tap() 回调不会改变这些值本身。这里只是记录日志,并没有使用其中的值.
/** 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', []))
    );
}
posted @ 2020-08-20 15:04  三重罗生门  阅读(435)  评论(0编辑  收藏  举报