您误解了Subscription 和add 的工作原理。
当你subscribe 到某个东西时,你会得到一个Subscription 对象,你可以调用unsubscribe()。这可以。但是,您没有正确分配值。您将Subscription 分配给const sub,然后您将其作为completion 块传递给add。
将Subscription.add 视为try/catch 的finally 块。不管Subscription 的结果是什么,当它是complete 时,传递给add 的块都会执行。将此用于任何清理任务。
subscriptions: Subscriptions[] = [];
ngOnDestroy() {
subscriptions.forEach((sub) => sub.unsubscribe());
}
deleteFile(id: any) {
const sub = this.fileCabinetService.deleteFile(id).subscribe(...);
this.subscriptions.push(sub);
sub.add(() => this.subscriptions.remove(sub));
}
要回答您关于何时使用unsubscribe 的问题,这实际上取决于deleteFile 的作用。如果deleteFile 方法在内部用一个值(或一组值)发出信号然后完成,则订阅将自动终止。如果它没有完成并悬空,那么您的订阅将继续存在。
考虑以下场景:
WallClock.subscribe((time) => console.log(time));
这个Subscription 永远不会被终止,因为时间(大概)会无限期地继续下去。相反,您需要手动控制何时终止。您可以通过以下几种方式做到这一点:
/* Get the current time, but don't bother listening to updates. */
WallClock.pipe(take(1)).subscribe((time) => console.log(time));
/* Continually update with the current time as long as the component is on screen
— Requires setting `this.staySubscribed = false` when you're leaving */
WallClock.pipe(takeWhile(() => this.staySubscribed)).subscribe((time) => console.log(time));
/* Continually update until you remember to unsubscribe
— Requires remembering to unsubscribe and can get verbose with multiple subscriptions
- Call `this.subscription.unsubscribe()` later */
this.subscription = WallClock.subscribe((time) => console.log(time));
如果您的deleteFile 像这样操作并不断报告值而没有明确的完成条件,您应该确保以某种方式终止订阅。很可能(基于函数的名称)这是一个自动终止的Subscription,不需要您做任何事情。如果您想真正安全,pipe(take(1)) 将为您提供保障。