Ali Adravi
Ali Adravi

Reputation: 22763

In Angular where to subscribe in service or in component & why?

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

Answers (1)

Guerric P
Guerric P

Reputation: 31825

In short:

  • Subscribing in a service: not really useful since a service is designed to hold a state, share this state and notify about state changes. A service is not designed to react to a state change
  • Subscribing in the component: unsafe when the Observable never completes and you don't manually unsubscribe in ngOnDestroy lifecycle hook
  • Let the framework subscribe for you (e.g: with async pipe). Safe because no risk of hanging subscriptions causing memory leaks. You can still expose a piped 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

Related Questions