Angular应用里HTTP请求的错误处理
生活随笔
收集整理的這篇文章主要介紹了
Angular应用里HTTP请求的错误处理
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
在需要進行錯誤處理的Angular應用里,從rxjs里導入catchError:
import { catchError, map, tap } from 'rxjs/operators'; getHeroes(): Observable<Hero[]> {return this.http.get<Hero[]>(this.heroesUrl).pipe(catchError(this.handleError<Hero[]>('getHeroes', [])));}The catchError() operator intercepts an Observable that failed. It passes the error an error handler that can do what it wants with the error.
catchError這個操作符可以攔截發生錯誤的Observable, 將其傳遞給應用程序指定的錯誤處理方法去。
handleError的方法實現:
/*** 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 infrastructureconsole.error(error); // log to console instead// TODO: better job of transforming error for user consumptionthis.log(`${operation} failed: ${error.message}`);// Let the app keep running by returning an empty result.return of(result as T);}; }要獲取更多Jerry的原創文章,請關注公眾號"汪子熙":
總結
以上是生活随笔為你收集整理的Angular应用里HTTP请求的错误处理的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Binlog的三个业务应用场景
- 下一篇: 使用npm安装TypeScript