angular - 如何在 Angular 的 http 服务中添加错误页面重定向
问题描述
我想在我的 api 调用服务中为 400 错误请求添加错误页面重定向:我的代码如下:
服务.ts:
getIncidents(customerId): Observable<any> {
return this.http.get<any>(this.incidentApiUrl + "?customer_id=" + customerId)
.pipe(
catchError(this.handleError)
);
}
private handleError(error: HttpErrorResponse) {
if (error.error instanceof ErrorEvent) {
console.log(error.error.message)
} else {
console.log(error.status)
}
return throwError(
console.log('Something is wrong!'));
};
}
我在哪里可以把重定向放在这里?
解决方案
您应该创建一个全局错误处理程序。我是这样实现的。
import { ErrorHandler, Injectable, Injector } from '@angular/core';
@Injectable()
export class GlobalErrorHandler implements ErrorHandler {
constructor(private logService: LoggerService, private router : Router) {
}
handleError(error) {
if(error.status == 404){
this.router.navigate(['/error-page']);
}
}
}
并添加到提供者NgModule
provide: LocationStrategy, useClass: HashLocationStrategy},
{
provide: ErrorHandler,
useClass: GlobalErrorHandler
}
推荐阅读
- c# - 更改数据源时,datagridview 行数据与旧数据源行数据重叠
- css - Clarity Design Datagrid 如何更改列宽
- corda - Corda 事务可以消除没有输出的状态吗?
- vue.js - VueJs + Element-ui:如何从输入中获取本机事件
- azure - 运行 ADF 管道而不在订阅级别分配“贡献者”角色
- c++ - 如何在c ++中检查两个数组,一个随机生成和用户输入的数组
- c++ - 如何在 Qt5 中将二进制数据写入标准输出
- ruby-on-rails - Factory_bot ActiveRecord::RecordInvalid
- java - 按属性对 JSON 输出进行分组
- python - python的List和CSV阅读器