【发布时间】:2020-06-16 16:35:53
【问题描述】:
我有一个角度组件,我定期从服务中请求值:
setInterval(() => {
this.updateValues();
}, 1000);
updateValues(): void {
if (this.isValuesUpdateRunning === false) {
this.isValuesUpdateRunning = true;
this.apiService.getCurrentValues().subscribe((data: any) => {
if (data != null) {
this.currentValues = data;
this.isValuesUpdateRunning = false;
}
});
}
}
我很确定我应该在某个地方取消订阅该服务,因为我确实通过这样做打开了很多订阅。我正在考虑使用异步管道,但我需要设置“isValueUpdateRunning”变量,如果我只是在模板中使用异步,这是不可能的。
此外,在 Angular 提供的“onDestroy”方法中取消订阅也无济于事,因为据我所知,只有在我离开页面时才会调用此方法。但我需要更频繁地关闭我的订阅,以防止保持数以千计的订阅处于打开状态。
我还尝试在设置我的值后立即关闭订阅,但是我没有在我的视图中获得任何值:
updateValues(): void {
if (this.isValuesUpdateRunning === false) {
this.isValuesUpdateRunning = true;
const sub = this.apiService.getCurrentValues().subscribe((data: any) => {
if (data != null) {
this.currentValues = data;
this.isValuesUpdateRunning = false;
}
});
// closing the subscription right here:
sub.unsubscribe();
}
}
你能帮忙吗?我的想法不多了。
【问题讨论】:
-
如果
this.apiService.getCurrentValues()正在使用 AngularHttpClient发出 http 请求,则无需取消订阅。 -
你没有得到价值,因为你在得到答案之前就退缩了。我同意上述关于 http 请求的评论。
-
@KurtHamilton 我正在使用 HttpClient,是的。这只是一个简单的获取请求。所以你认为我根本不需要退订?我认为除非你使用异步管道,否则它总是需要的。
-
@Manuela 取消订阅并没有什么坏处,事实上,如果您不希望 subscribe 中的逻辑运行,那么如果 api 调用挂起并且您已移动到应用程序的不同部分而不是这是必须的。