为什么 Angular 不自动取消订阅所有活动订阅,也许是在组件销毁时?



或者应该是RxJS来处理活动订阅?不管是谁,为什么它不自动取消订阅所有活动订阅,或者至少在组件销毁或某个最终事件中提供一个自动取消订阅或取消订阅所有订阅的标志?

管理订阅取决于您作为开发人员。如何管理订阅取决于您和您的团队。

您可以通过利用RxJS的运算符和Angular的方法使取消订阅变得更容易

例如,我们可以有一个扩展Unsubscribe并实现OnDestroy的组件。

export class AppComponent  extends Unsubscribe  implements OnDestroy{...}

Unsubscribe类允许任何组件有一个主题来取消订阅每个Observable

class Unsubscribe {
public readonly destroy = new Subject<void>()

protected destroySubs() {
this.destroy.next()
}
}

我们拥有的任何订阅(不在我们的模板中(都将使用takeUntil运算符来保持订阅有效,直到组件被销毁

@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent  extends Unsubscribe  implements OnDestroy{
name = 'Angular ' + VERSION.major;
someSubscription: Subscription
constructor() {
super()
this.someSubscription = interval(1000).pipe(takeUntil(this.destroy)).subscribe(console.log)
setTimeout(() => {
this.ngOnDestroy()
}, 5000)
}
ngOnDestroy() {
this.destroySubs()
}
}

下面是一个代码示例。尝试在chrome中运行此操作,并观察控制台中发生的情况:https://stackblitz.com/edit/angular-unsbscribe-ex?file=src/app/app.component.ts

最新更新