ObjectUnsubscribedError when trying to prevent subscribing twice

前端 未结 2 1377
Happy的楠姐
Happy的楠姐 2020-12-05 04:18

I have a Service and a component that uses it:

  • PagesService
  • PagesListComponent

In the PagesService

2条回答
  •  春和景丽
    2020-12-05 04:28

    .subscribe() returns a Subscription

    • You should use this to unsubscribe


    e.g. Parent has a reloadSubject: Subject;

    • child1 -> subscribes
    • child2 -> subscribes

    child1 - "WORKS" -> unsubscribe's his subscription

    ngOnInit{ 
      sub: Subscription = parent.subscribe();
    }
    onDestroy{
      this.sub.unsubscribe();
    }
    


    child2 - "DOES NOT WORK" -> unsubscribe's the whole parent

    ngOnInit{ 
      parent.subscribe();
    }
    
    onDestroy{
      parent.unsubscribe();
    }
    

    If you call unsubscribe on the parent both children are gone.
    If you unsubscribe the Subscription that you get from the .subscribe() then only one child is unsubscribed.

    Please correct me if I am wrong!

提交回复
热议问题