ObjectUnsubscribedError when trying to prevent subscribing twice
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(); // <-------}
.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!