Skip to content

Instantly share code, notes, and snippets.

@pgiemza
Created June 5, 2017 06:55
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pgiemza/1b81188e56ff24c977e605f9feb1d2f2 to your computer and use it in GitHub Desktop.
Save pgiemza/1b81188e56ff24c977e605f9feb1d2f2 to your computer and use it in GitHub Desktop.
import { OnDestroy } from '@angular/core';
import { Subject } from 'rxjs/Subject';
export abstract class BaseComponent implements OnDestroy {
protected destroyed$: Subject<boolean> = new Subject();
protected constructor() {}
ngOnDestroy(): void {
this.destroyed$.next(true);
this.destroyed$.complete();
}
}
@wen-dell
Copy link

wen-dell commented Feb 8, 2018

Hi. To use this class, what I need to do is just extends this class?

And, can I use it on my project too?

@bentaly
Copy link

bentaly commented Feb 21, 2018

I think you're supposed to extend this base class, and the OnDestroy method gets called for you. So I think you use this.http.takeUntil(detroyed$), for example

@jsantoru
Copy link

very nice, thanks

@vcfvct
Copy link

vcfvct commented Jun 16, 2018

Elegantly solution! Looks cleaner than the custom annotation way.
Thanks for sharing!

@scriby
Copy link

scriby commented Jul 19, 2018

If using this pattern you have to be careful if any of the derived components implement their own ngOnDestroy.

class Component extends BaseComponent {
  ngOnDestroy() {
    // oops, now ngOnDestroy on the base component won't get called and observables are probably leaking
  }
}

You'll have to remember to call super:

class Component extends BaseComponent {
  ngOnDestroy() {
    super.ngOnDestroy(); // can't forget this
  }
}

The chance for human error in this pattern makes it a little less appealing.

@VictorCoding
Copy link

I really like this approach. Below is a stackblitz showing this in action.

https://stackblitz.com/edit/angular-zjppzp

@gmavritsakis
Copy link

This should have issues with AOT compilation, see here angular/angular#19145

@dchirutac
Copy link

Clever, implemented with success. Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment