André
André

Reputation: 2016

Do I need to use takeUntilDestroyed pipe if I open a subscribtion in the Angular app (root) component?

In Angular is good practice to call unsubscribe in open subscriptions on component destroy:

import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
 
export class Component implements OnInit{
  public data;
 
  constructor(private service: DataService) {
    this.service.getData()
      .pipe(takeUntilDestroyed())
      .subscribe(response => this.data = response);
  }
}

However, I was wandering if this is necessary when I'm making a subscription in the Angular app (root) component itself?
Is it safe to assume that if this component is destroyed, the whole app will be destroyed and the subscription will be closed by default?

What did I try and what am I expecting?
I'm not calling takeUntilDestroyed in the app component (which is the root component of my Angular application). I'm expecting that the subscription won't remain open after the component is destroyed.

Upvotes: 0

Views: 311

Answers (2)

mbirali
mbirali

Reputation: 66

A good practice is to use ngOnInit and subscribe directly on the template using the Async pipe, this way the subscription will be closed after the component is destoryed !

So your component.ts will look like the snippet bellow, all you need is an async pipe on the template:

export class Component implements OnInit {
  data$;

  constructor(private service: DataService) { }

  ngOnInit { 
    this.data$ = this.service.getData();
  }
}

Hope its clear for you !

Upvotes: 0

Roman P.
Roman P.

Reputation: 373

However, I was wandering if this is necessary when I'm making a subscription in the Angular app (root) component itself? Is it safe to assume that if this component is destroyed, the whole app will be destroyed and the subscription will be closed by default?

I would say it makes no big difference in the (root) app, because the root app will be destroyed if you close your browser or the tab, in that case the whole app get's destroyed and so the observerable too.

But in your example you get the data from a service and I guess you use the HttpClient to talk to some REST endpoints. The observables created by the HttpClient eg. get/post/put/... are completed by default when the request is finished, that means they will be automatically unsubscribed.

You have only to unsubscribe by yourself if it's a observable which is emitting multiple values over time and does not complete eg. a Subject.

Upvotes: 1

Related Questions