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?