Reputation: 22763
This question is very common, some prefer to use in service some in component:
Angular 2 subscribe from component or service?: it says never do the manual subscription means from component!
If we don't want any data then why we need to subscribe(in service)? and when the unsubscribe will be called?
If we are subscribing from component:
this.serviceA.getMethodObservable().subscribe(data => {
this.data = data;
});
Note: Subscription is never unsubscribed!
If Observable could not complete by its own, then whole component, template and all associated objects, will live in memory forever.
For this we use
// onDestroy: subject
this.serviceA.getMethodObservable()
.pipe(takeUntil(this.onDestroy))
.subscribe(data => {
this.data = data;
});
ngOnDestroy() {
this.onDestroy.next();
}
It is a question to discuss in detail and understand the pros and cons any approach! So my question is WHICH ONE & WHY?
Upvotes: 7
Views: 19193
Reputation: 31825
In short:
Observable
never completes and you don't manually unsubscribe in ngOnDestroy
lifecycle hookasync
pipe). Safe because no risk of hanging subscriptions causing memory leaks. You can still expose a pipe
d Observable
to the template and perform various operations on component level thanks to the rxjs operators without risking any memory leak (even if the callbacks refer to this
)Upvotes: 9