Arp*_*mar 3 javascript http angular
我正在使用 Angular 7,并且在我的应用程序中使用了 HTTP 拦截器。
我无法跟踪该 HTTP 拦截器中的 401 状态代码。
我尝试了进站catchError,tap但它给出了状态 0,我想要 401 。
我的代码在这里:
return next.handle(request).pipe(tap(event => {
console.log('the ev is :', event);
if (event instanceof HttpResponse) {
this.onEnd();
}
}, err => {
if (err instanceof HttpErrorResponse) {
console.log('the eeeeeee is :', err);
this.onEnd();
// User logged out
if (err.status === 401) {
this.router.navigate(['logout']);
}
}
})).pipe(catchError(error => {
console.log('the ee is :', error);
return Observable.throw(error);
}));
Run Code Online (Sandbox Code Playgroud)
谢谢。
该方法中有一个错误处理程序tap,然后有一个单独的管道catchError. 除非您打算对收到的响应(即 http 200)采取行动。一个简单的拦截器实现是:
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(request).pipe(
catchError(err => {
if (err instanceof HttpErrorResponse) {
if (err.status === 401 || err.status === 403) {
// Invalidate user session and redirect to login/home
}
// return the error back to the caller
return throwError(err);
}
}),
finalize(() => {
// any cleanup or final activities
})
);
}
Run Code Online (Sandbox Code Playgroud)