我有一个授权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 时,我将用户重定向到登录页面,但错误仍然转到服务,并且在那个服务中我显示错误消息,并且这个消息在登录时显示页。所以我想更改响应或在 if (err instanceof HttpErrorResponse && err.status === 401) {
block 中做一些事情,在这种情况下不返回错误。
return Observable.empty();
不工作
最佳答案
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);
});
}
}
关于Angular 拦截器更改响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46329944/