Angular 4+ ngOnDestroy() in service - destroy observable

mperle picture mperle · Aug 26, 2017 · Viewed 80.1k times · Source

In an angular application we have ngOnDestroy() lifecycle hook for a component / directive and we use this hook to unsubscribe the observables.

I want to clear / destory observable that are created in an @injectable() service. I saw some posts saying that ngOnDestroy() can be used in a service as well.

But, is it a good practice and only way to do so and When will it get called ? someone please clarify.

Answer

Estus Flask picture Estus Flask · Aug 27, 2017

OnDestroy lifecycle hook is available in providers. According to the docs:

Lifecycle hook that is called when a directive, pipe or service is destroyed.

Here's an example:

@Injectable()
class Service implements OnDestroy {
  ngOnDestroy() {
    console.log('Service destroy')
  }
}

@Component({
  selector: 'foo',
  template: `foo`,
  providers: [Service]
})
export class Foo implements OnDestroy {
  constructor(service: Service) {}

  ngOnDestroy() {
    console.log('foo destroy')
  }
}

@Component({
  selector: 'my-app',
  template: `<foo *ngIf="isFoo"></foo>`,
})
export class App {
  isFoo = true;

  constructor() {
    setTimeout(() => {
        this.isFoo = false;
    }, 1000)
  }
}

Notice that in the code above Service is an instance that belongs to Foo component, so it can be destroyed when Foo is destroyed.

For providers that belong to root injector this will happen on application destroy, this is helpful to avoid memory leaks with multiple bootstraps, i.e. in tests.

When a provider from parent injector is subscribed in child component, it won't be destroyed on component destroy, this is component's responsibility to unsubscribe in component ngOnDestroy (as another answer explains).