1. 程式人生 > 實用技巧 >Angular(15) - 從服務端獲取資料 - 官方教程英雄指南之服務呼叫HTTP資料 (詳細解說)

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', []))
    );
}