如何在API调用中对400错误的请求进行页面重定向?在角 [英] How to have a page redirect on a 400 bad request in api call? In Angular
本文介绍了如何在API调用中对400错误的请求进行页面重定向?在角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我从api调用中收到400错误请求时,我尝试添加页面重定向.我要在哪里做?在服务或component.ts中:到目前为止,我的代码是:
I am trying to add a page redirect to when I get a 400 bad request from an api call. Where would I do this? In the service or the component.ts: My code so far is:
Service.ts
getIncidents(customerId): Observable<any> {
return this.http.get<any>(this.incidentApiUrl + "?customer_id=" + customerId)
.pipe(
catchError(this.handleError)
);
}
Component.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
You can create ErrorInterceptor from HttpInterceptor
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);
}))
}
}
,并将其添加到模块的提供程序中
and add the same in the providers of the module
providers: [
{ provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },
],
这篇关于如何在API调用中对400错误的请求进行页面重定向?在角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文