首页 > 解决方案 > 当我路由到另一个组件时,我在一个组件中有 API 调用挂起,必须取消之前的 API 调用

问题描述

我有一个问题,比如我在一个组件中调用 API 假设它处于挂起状态,现在我正在路由到另一个页面,需要取消在上一个路由中进行的上一个 API 调用

我尝试使用 HttpCancelInterceptor

@Injectable()
export class HttpCancelInterceptor implements HttpInterceptor {
  constructor(private httpCancelService: HttpCancelService) { }

  intercept<T>(req: HttpRequest<T>, next: HttpHandler): Observable<HttpEvent<T>> {
    return next.handle(req).takeUntil(this.httpCancelService.onCancelPendingRequests())
  }
}

@Injectable()
export class HttpCancelService {
  private cancelPendingRequests$ = new Subject<void>()

  constructor() { }

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

  public onCancelPendingRequests() {
    return this.cancelPendingRequests$.asObservable()
  }

}

在 app.component.ts

让它适用于我这样写的所有路线

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

我无法截取我用示例解释的 API

当我遵循上述代码时出现的结果

第 1 页:当我路由到另一个页面时,调用 3 API 都处于挂起状态(计数、金额、公告)只有 1 个 API 被取消

第 2 页:计数 API - 取消金额 API - 待定公告 API - 待定


预期结果:

第 1 页:计数、金额、公告 API - 处于待处理状态
第 2 页:计数、金额、公告 API - 已取消状态

所有取消都需要在 app.component.ts 中作为通用路由更改进行处理

请帮我解决这个问题

标签: angularapidestroy

解决方案


您应该取消订阅第一个组件中的订阅。

向所有在其类代码中调用的private ngUnsubscribe = new Subject();组件添加一个字段。.subscribe()Observables

然后调用方法this.ngUnsubscribe.next(); this.ngUnsubscribe.complete();ngOnDestroy()

例子:

import { Component, OnDestroy, OnInit } from '@angular/core';
// RxJs 6.x+ import paths
import { filter, startWith, takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs';
import { Myservice} from '../my.service';

@Component({
    selector: 'test-component',
    templateUrl: './test.component.html'
})
export class TestComponent implements OnDestroy, OnInit {
    private ngUnsubscribe = new Subject();

    constructor(private myService: Myservice) { }

    ngOnInit() {
        this.myService.getData()
            .pipe(
               startWith([]),
               filter(data=> data.length > 0),
               takeUntil(this.ngUnsubscribe)
            )
            .subscribe(data=> console.log(data));

        this.myService.getAnotherData()
            .pipe(takeUntil(this.ngUnsubscribe))
            .subscribe(anotherData=> console.log(anotherData));
    }

    ngOnDestroy() {
        this.ngUnsubscribe.next();
        this.ngUnsubscribe.complete();
    }
}

将运算符添加为最后一个很重要,takeUntil以防止运算符链中的中间可观察对象泄漏。


推荐阅读