如何在angular5中取消Http Interceptor中的请求?

时间:2018-05-18 10:38:01

标签: rxjs angular5 angular-http-interceptors request-cancelling

我的角度应用程序有一个名为'listdata.component.ts'的组件。在此组件的ngOnInit()中,发生了2个api调用。但是,当针对2个请求获得401响应时,注销api调用将发生2次。我的拦截器代码

@Injectable()
export class TokenInterceptor implements HttpInterceptor {
    notificationItem: any;
    constructor(public authService: AuthGuardService, private router: Router, private notification: NotificationService) { }

    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        if (this.authService.tokenValid()) {
            const authReq = request.clone({ headers: request.headers.set("Authorization", 'Bearer ' + this.authService.getToken()) });
            return next.handle(authReq).do((event: HttpEvent<any>) => {
            }, err => {

                if (err instanceof HttpErrorResponse) {

                    if (err.status === 401) {

                        if(authReq.url.indexOf('/logout') > -1){
                            localStorage.clear();
                            this.router.navigate(['login']);
                        }
                        else
                        {

                this.authService.logout()

                        }
                    }
                }
            });
        }
        else{
            return next.handle(request);
        }
    }
}

我想在一次401响应后取消所有401请求,并且只注册一次注销。如果takeUntil()运算符可以解决我的问题吗?。提前谢谢。

0 个答案:

没有答案