使用Angular Interceptor取消所有待处理的http请求。

问题描述 投票:0回答:1

我的拦截器

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();
    }

但问题是,当我把途径改为产生多个初始请求的途径时,就会取消之前途径的待处理请求,并取消当前途径的请求。

怎样才能做到只取消之前途径的待处理请求,不触及当前途径的任何请求呢?

谢谢!!

angular http request httpclient interceptor
1个回答
1
投票

当你导航到新的位置时,你会发现,在你的网站上,有一个新的位置。ActivationEnd 事件发生在组件加载之后。NavigationStart 你取消了所有的事件,然后新的组件加载。

所以你的拦截器ctor应该是这样的。

router.events.subscribe(event => {
     if (event instanceof NavigationStart ) {
          this.httpCancelService.cancelPendingRequests();
     }
});

重要的:可能我建议的事件可能不适合你,看看文档,看看什么最适合你。https:/angular.ioapirouterEvent。

© www.soinside.com 2019 - 2024. All rights reserved.