Angular 4+ ngOnDestroy() in service - destroy observable

AngularRxjsObservableAngular Services

Angular Problem Overview

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.

Angular Solutions

Solution 1 - Angular

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:

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

  selector: 'foo',
  template: `foo`,
  providers: [Service]
export class Foo implements OnDestroy {
  constructor(service: Service) {}
  ngOnDestroy() {
    console.log('foo destroy')

  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).

Solution 2 - Angular

Create a variable in your service

subscriptions: Subscriptions[]=[];

Push each of your subscribe to the array as


Write a dispose() method

this.subscriptions.forEach(subscription =>subscription.unsubscribe())

Call this method from your component during ngOnDestroy


Solution 3 - Angular

I prefer this takeUntil(onDestroy$) pattern enabled by pipable operators. I like that this pattern is more concise, more clean, and it clearly conveys the intent to kill a subscription upon execution of the OnDestroy lifecycle hook.

This pattern works for services as well as components subscribing to injected observables. The skeleton code below should give you enough detail to integrate the pattern into your own service. Imagine you're importing a service called InjectedService...

import { InjectedService } from 'where/it/lives';
import { Injectable, OnDestroy } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { takeUntil } from 'rxjs/operators';
import { Subject } from 'rxjs/Subject';

export class MyService implements OnDestroy {

  private onDestroy$ = new Subject<boolean>();

    private injectedService: InjectedService
  ) {
    // Subscribe to service, and automatically unsubscribe upon `ngOnDestroy`
    ).subscribe(latestTask => {
      if (latestTask) {

  ngOnDestroy() {

The topic of when/how to unsubscribe is covered extensively here:

Solution 4 - Angular

Just to clarify - you don't need to destroy Observables but only the subscriptions made to them.

It seems like others have pointed out that you are now able to use ngOnDestroy with services as well. Link:

Solution 5 - Angular

Caution if using tokens

In trying to make my application as modular as possible I'll often use provider tokens to provide a service to a component. It seems that these do NOT get their ngOnDestroy methods called :-(


export const PAYMENTPANEL_SERVICE = new InjectionToken<PaymentPanelService>('PAYMENTPANEL_SERVICE');

With a provider section in a component:

     useExisting: ShopPaymentPanelService

My ShopPaymentPanelService does NOT have its ngOnDestroy method called when the component is disposed. I just found this out the hard way!

A workaround is to provide the service in conjunction with useExisting.


       useExisting: ShopPaymentPanelService

When I did this the ngOnDispose was called as expected.

Not sure if this is a bug or not but very unexpected.

Solution 6 - Angular

Create a variable in your service:

private subscriptions$ = new Subscription();

Add each of your subscriptions to observable in constructor (or in ngOnInit lifecycle hook)

ngOnInit() {

Call this method from your component on destroy to unsubscribe from all subscriptions and child subscriptions.


Solution 7 - Angular

I recommend using .pipe(take(1)).subscribe(). To avoid setting up an ongoing subscription.


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmperleView Question on Stackoverflow
Solution 1 - AngularEstus FlaskView Answer on Stackoverflow
Solution 2 - AngularAravindView Answer on Stackoverflow
Solution 3 - AngularMatthew MarichibaView Answer on Stackoverflow
Solution 4 - AngularapeshevView Answer on Stackoverflow
Solution 5 - AngularSimon_WeaverView Answer on Stackoverflow
Solution 6 - AngularSunday Power InemesitView Answer on Stackoverflow
Solution 7 - AngularmobiblaizeView Answer on Stackoverflow