3

我的 Angular 应用程序有一个名为“listdata.component.ts”的组件。在该组件的 ngOnInit() 中,发生了 2 个 api 调用。但是当 2 个请求得到 401 响应时,会发生 2 次注销 api 调用。我的拦截器代码

@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() 运算符可以解决我的问题?提前谢谢。

4

0 回答 0