如果页面正在导航,如何销毁调用?

How to Destroy the call if the page is navigate?

我用 concatmap 调用了多个请求。以下是我的代码

getGeneDetail() {
    const obs = from(this.genes);
    obs.pipe(
        concatMap(res => {
            const ep = this.callService.getAll(this.resource + '/' + res.name + '/status');
            return ep.pipe(map(r => {
                this.tableData[res.i]['x'] = r.gene[x].xpos;
            }));
        })
    ).subscribe();
}

并且 this.genes 包含以下数据

    [
        {
            "name": "tim",
            "i": 0
        },
        {
            "name": "keratin",
            "i": 1
        },
        {
            "name": "isomerase",
            "i": 2
        },
        {
            "name": "evps",
            "i": 3
        },
        {
            "name": "ank1",
            "i": 4
        },
        {
            "name": "cdsn",
            "i": 5
        }
        .. ,more than 100 entities

以上代码运行良好。但是,如果我导航到 API 仍在调用的另一个组件,就会出现问题。那么如何在页面导航时阻止调用?

您需要存储订阅,然后在ngOnDestroy中取消订阅。否则,订阅仍处于打开状态,并将继续监听变化

geneSub: Subscription;
getGeneDetail() {
    const obs = from(this.genes);
    this.geneSub = obs.pipe(
        concatMap(res => {
            const ep = this.callService.getAll(this.resource + '/' + res.name + '/status');
            return ep.pipe(map(r => {
                this.tableData[res.i]['x'] = r.gene[x].xpos;
            }));
        })
    ).subscribe();
}
ngOnDestroy(){
  if(this.geneSub) this.geneSub.unsubscribe();
}

您可以在您的管道中使用 takeUntil 并创建一个 'reset' 主题,该主题在 ngOnDestroy 中是完整的。详情请看这篇文章:https://ncjamieson.com/avoiding-takeuntil-leaks/