ObjectUnsubscribedError when trying to prevent subscribing twice

前端 未结 2 1378
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!

    0 讨论(0)
  • 2020-12-05 04:38

    I would get the subscription and unsubscribe on it this way and not on the subject directly:

    ngOnInit() {
      this.pages$ = this.pagesService.getPagesListener();
      this.subscription = this.pages$.subscribe((pages) => { // <-------
        this.pages = pages; console.log(pages);
      });
      this.pagesService.getAll();
    }
    
    ngOnDestroy() {
        this.subscription.unsubscribe(); // <-------
    }
    
    0 讨论(0)
提交回复
热议问题