Created
June 5, 2017 06:55
-
-
Save pgiemza/1b81188e56ff24c977e605f9feb1d2f2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
} | |
} |
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
very nice, thanks
Elegantly solution! Looks cleaner than the custom annotation way.
Thanks for sharing!
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.
I really like this approach. Below is a stackblitz showing this in action.
This should have issues with AOT compilation, see here angular/angular#19145
Clever, implemented with success. Thanks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi. To use this class, what I need to do is just extends this class?
And, can I use it on my project too?