Angular应用里HTTP请求的错误处理
2023-09-14 09:03:56 时间
在需要进行错误处理的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 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);
};
}
要获取更多Jerry的原创文章,请关注公众号"汪子熙":
相关文章
- [Angular 8 Unit Testing] Angular 8 Unit Testing -- service
- [Angular] Angular CDK Intro
- [Angular 2] Order Dynamic Components Inside an Angular 2 ViewContainer
- [Angular 2] DI in Angular 2 - 1
- [Angular 8 Unit testing] Testing a smart component with service injection -- 1
- [Angular] Upgrading to RxJS v6
- [Angular] Stagger animation v4.3.3
- 让 Angular 应用动起来!
- 运行在 CCV2 环境上的 Angular 服务器端渲染应用的性能瓶颈分析
- Angular NgRx MemoizedSelector的类型定义学习
- SAP Spartacus 中 Angular json pipe 的工作原理
- Angular SSR 应用启动时的一些保护措施
- 关于 Angular 应用的入口
- Angular Remove me测试应用的工作原理
- Angular 服务器端渲染应用一个常见的内存泄漏问题
- 给 Angular 服务器端渲染应用设置一个渲染超时时间
- 关于Angular @Injectable的几种测试情况
- 一个基于ngrx的Angular图书搜索应用,带网络请求
- Angular 页面元素的DOM级别的删除过程
- Angular async pipe在Component html模板中的一个实际应用
- Angular Component 开发时属性和运行时属性的对照
- 使用jasmine.createSpyObj具有依赖关系的Angular服务进行单元测试
- 在Angular应用里使用Redux
- Angular应用的依赖注入调试
- Angular应用的入口
- 给Angular初学者介绍一个非常方便的例子学习网站
- 【响应式编程的思维艺术】 (5)Angular中Rxjs的应用示例
- socket.io+angular.js+express.js做个聊天应用(三)
- 主流前端框架对比:Vue.js , React, Angular.js