我为我的角应用程序编写了一个错误拦截器,以便在检测到401时将用户路由到登录页面。
奇怪的是,永远不会调用错误块。只有条目和成功控制台日志条目位于我的控制台中。
知道可能出现什么问题吗?
import { Injectable } from '@angular/core';
import { HttpInterceptor, HttpRequest, HttpHandler, HttpEvent, HttpErrorResponse } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/do';
import {Router} from '@angular/router';
import { HTTP_INTERCEPTORS } from '@angular/common/http';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private router: Router) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('interceptor called');
return next.handle(req).do(event => {
console.log('interceptor in success', event);
}, err => {
console.log('interceptor in error', err);
if (err instanceof HttpErrorResponse && err.status === 401) {
this.router.navigate(['/login']);
}
});
}
}
export const errorInterceptorProvider = {
provide: HTTP_INTERCEPTORS,
useClass: ErrorInterceptor,
multi: true,
};
拦截器集成在我的app模块中:
providers: [
...
errorInterceptorProvider
],
答案 0 :(得分:0)
应该可以看到https://plnkr.co/edit/mQnrJQarp4wRaohKNzre?p=preview
另一种选择是使用catch
运算符:
...
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/empty';
import 'rxjs/add/observable/throw';
import 'rxjs/add/operator/finally';
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {
constructor(private router: Router) {}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
console.log('interceptor called');
return next.handle(req)
.do(event => {
console.log('interceptor in success', event)
})
.catch(err => {
console.log('interceptor in error', err);
if (err instanceof HttpErrorResponse && err.status === 401) {
this.router.navigate(['/login']);
}
return Observable.throw(err);
// or return Observable.empty();
})
.finally(() => {
console.log('finally');
});
}
}
<强> Plunker Example 强>