我需要取消订阅路由器的事件可观察对象吗?

huangapple go评论109阅读模式
英文:

Do I need to Unsubscribe Router's event observable

问题

这意味着所有组件的成员也会被销毁。

它明确表示ActivatedRoute不需要被取消订阅,但对于Router的可观察对象(如events),仍然存在困惑。

英文:

I have confusion with Angular docs statement, which says "This means all the component's members will also be destroyed"

Doc Link

so the question is do i need to unsubscribe it or not,

  1. constructor(
  2. private readonly router: Router
  3. ) {
  4. this.router.events.subscribe((event: Event) => {
  5. if (event instanceof NavigationEnd) {

It clearly says about ActivatedRoute need not to be unsubscribed, but keeps the confusion for Router observable like events.

答案1

得分: 2

这是关于 ActivatedRoute 而不是 Router 的讨论,解决方法是执行以下操作:

  1. eventSubscription: Subscription;
  2. ...
  3. this.eventSubscription = this.router.events.subscribe((event: Event) => {
  4. ...
  5. ngOnDestroy() {
  6. this.eventSubscription.unsubscribe()
  7. }
英文:

It is talking about ActivatedRoute but not Routerthe solution would be to do

  1. eventSubscription:Subscription;
  2. ...
  3. this.eventSubscription = this.router.events.subscribe((event: Event) => {
  4. ...
  5. ngOnDestroy () {
  6. this.eventSubscription.unsubscribe()
  7. }

答案2

得分: 0

是的,您需要取消订阅路由器事件,因为Router是全局可重用的提供程序,所以即使在组件销毁后,Router仍将在DI中存在,带有所有订阅。

英文:

Yes, you need to usubscribe from Router events because Router is global reusable provider, so even after the component destroy Router will be living in DI with all subcriptions.

huangapple
  • 本文由 发表于 2023年8月10日 19:17:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/76875228.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定