Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/28.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Angular拦截器取消所有挂起的http请求_Angular_Http_Request_Httpclient_Interceptor - Fatal编程技术网

使用Angular拦截器取消所有挂起的http请求

使用Angular拦截器取消所有挂起的http请求,angular,http,request,httpclient,interceptor,Angular,Http,Request,Httpclient,Interceptor,我的拦截器: constructor(router: Router, private httpCancelService: HttpCancelService) { router.events.subscribe(event => { if (event instanceof ActivationEnd) { this.httpCancelService.cancelPendingRequests();

我的拦截器:

constructor(router: Router,
        private httpCancelService: HttpCancelService) {
        router.events.subscribe(event => {
            if (event instanceof ActivationEnd) {
                this.httpCancelService.cancelPendingRequests();
            }
        });
    }

    intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> {
        return next.handle(req).pipe(takeUntil(this.httpCancelService.onCancelPendingRequests()));
    }
我的取消服务:

 private pendingHTTPRequests$ = new Subject<void>();

    constructor() { }


    public cancelPendingRequests() {
        this.pendingHTTPRequests$.next();
    }

    public onCancelPendingRequests() {
        return this.pendingHTTPRequests$.asObservable();
    }
它对我来说非常有效,但我的问题是,当我将路由更改为生成多个初始请求的路由时,它会取消我以前路由的挂起请求,并取消我当前路由的请求

我该怎么做才能只取消上一条路线的未决请求,而不触及当前路线的任何请求


谢谢

当您导航到新位置时,组件加载后会发生ActivationEnd事件。 如果侦听NavigationStart事件,则会取消所有事件,然后加载新组件

因此,您的拦截器应该如下所示:

router.events.subscribe(event => {
     if (event instanceof NavigationStart ) {
          this.httpCancelService.cancelPendingRequests();
     }
});
重要: 我建议的活动可能不适合您,请查看文档,看看哪些活动最适合您: