use*_*934 5 angular-http-interceptors angular angular4-httpclient
我有一个认证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();
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
这个拦截器工作正常,但是当我得到401我将用户重定向到登录页面时,但错误仍然发送到服务,并且在该服务中我显示错误消息,并且这个消息显示在登录页面.所以我想改变响应或做一些if (err instanceof HttpErrorResponse && err.status === 401) {阻止,在这种情况下不返回错误.
return Observable.empty();
Run Code Online (Sandbox Code Playgroud)
不管用
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);
});
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2945 次 |
| 最近记录: |