如果页面导航,如何销毁呼叫?

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

我使用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仍在调用的另一个组件,就会出现问题。因此,如果页面导航,如何防止通话?

angular rxjs6
1个回答
0
投票

您需要存储订阅,然后在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();
}
© www.soinside.com 2019 - 2024. All rights reserved.