我有一个特别的HttpInterceptor
import {HttpErrorResponse, HttpEvent, HttpHandler, HttpInterceptor,
HttpRequest} from '@angular/common/http';
import {AuthService} from '../service/auth.service';
import {Observable} from 'rxjs/Observable';
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService,
private router: Router) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authHeader = this.authService.getToken();
const clone = req.clone({headers: req.headers.set('Authorization',authHeader)});
return next.handle(clone).do(() => {
}, err => {
console.log(err);
if (err instanceof HttpErrorResponse && err.status === 401) {
this.authService.clearToken();
this.router.navigate(['/auth/signin']);
return Observable.empty();
}
});
}
}这个拦截器工作得很好,但是当我得到401时,我将用户重定向到登录页面,但是错误仍然会传递给服务,而在该服务中,我显示的是错误msg,这个msg显示在signin页面上。因此,我希望在if (err instanceof HttpErrorResponse && err.status === 401) {块中更改响应或执行一些操作,以便在本例中不返回错误。
return Observable.empty();没有用
发布于 2017-09-20 19:12:37
next.handle(clone).do() -这就是导致这种行为的原因。do()操作符只打算提供副作用,但实际上并不会影响数据流和可观察管道中的错误处理。本质上,它是说“当这种情况发生时,请做这个和那个,然后继续,就好像根本没有do()节一样”。如果您想要抑制错误,那么您需要使用catch()运算符。
代码将几乎相同:
@Injectable()
export class AuthInterceptor implements HttpInterceptor {
constructor(private authService: AuthService,
private router: Router) {
}
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
const authHeader = this.authService.getToken();
const clone = req.clone({headers: req.headers.set('Authorization',authHeader)});
return next.handle(clone).catch(err => { // <-- here
console.log(err);
if (err instanceof HttpErrorResponse && err.status === 401) {
this.authService.clearToken();
this.router.navigate(['/auth/signin']);
return Observable.empty();
}
// we must tell Rx what to do in this case too
return Observable.throw(err);
});
}
}https://stackoverflow.com/questions/46329944
复制相似问题