angular - 如何在 api 调用中对 400 错误请求进行页面重定向?在角
问题描述
当我从 api 调用收到 400 错误请求时,我正在尝试添加页面重定向。我会在哪里做这个?在服务或component.ts中:到目前为止我的代码是:
服务.ts
getIncidents(customerId): Observable<any> {
return this.http.get<any>(this.incidentApiUrl + "?customer_id=" + customerId)
.pipe(
catchError(this.handleError)
);
}
组件.ts
private getIncidents() {
this.service.getIncidents(this.customer_id).subscribe((data) => {
this.loading = true;
console.log('Data' + data);
this.showTable = this.data = data.result;
this.loading = false;
console.log('Result - ', data);
console.log('data is received');
this.errorApi = data.result == null || data.result === 0 || data.result.length === 0;
})
}
解决方案
您可以从 HttpInterceptor 创建 ErrorInterceptor
import { Injectable } from '@angular/core';
import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
import { Router } from '@angular/router';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(catchError(err => {
if (err.status === 400) {
// redirect to some page
this.router.navigate(['/somepage']);
}
const error = err.error || err.statusText;
return throwError(error);
}))
}
}
并在模块的提供者中添加相同的内容
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
],
推荐阅读
- javascript - 如果2个对象相互碰撞,JavaScript如何停止动画
- javascript - 如何在 React Native 中的两个独立功能组件之间传递状态变量?
- pytest - 如何在一个skipif中跳过一组PyTest
- vue.js - 将事件绑定到自定义组件
- css - 将 CSS 添加到 Blazor WebAssembly 视图
- android - 在 Text Jetpack compose 上实现长按
- python - 当在请求中的某个字段内建模数据时,如何使用具有多对多字段和外键的 Django Rest Framework 模型序列化创建?
- javascript - 将 formData 传递给 Express 中间件,Req.body 返回空对象
- c# - WinForms - 当应用程序启动时没有可用的 Internet 连接时 mscorlib.dll 中的 System.Reflection.TargetInvocationException
- node.js - 部署到 Beanstalk 时遇到问题