Last active
August 21, 2020 02:05
-
-
Save AlexAegis/adbee188fc9cde8517b5338394541ad7 to your computer and use it in GitHub Desktop.
Angular subscription handler, unsubscribes when the component is destroyed
This file contains 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 { Subscription } from 'rxjs'; | |
/** | |
* Adds a subscription object and a default OnDestroy hook to the child component | |
* | |
* If ngOnDestroy is is overriden in the child component don't forget to call | |
* ```typescript | |
* super.ngOnDestroy(); | |
* ``` | |
*/ | |
export class BaseDirective implements OnDestroy { | |
protected subscriptions = new Subscription(); | |
/** | |
* Add the subsription to a directive wide subscription object | |
* which will be unsubscribed OnDestroy by default making | |
* all the added subscriptions unsubsribe | |
* | |
* @param subscription to be torn down on destroy | |
*/ | |
protected set teardown(subscription: Subscription) { | |
this.subscriptions.add(subscription); | |
} | |
public ngOnDestroy(): void { | |
this.subscriptions.unsubscribe(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment