简体   繁体   中英

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?

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 (eg: with async 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 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM