Skip to content

Instantly share code, notes, and snippets.

@Jonatthu
Created January 4, 2018 18:15
Show Gist options
  • Save Jonatthu/d9d7275aa928e4aa24ea2bd44e3aa11d to your computer and use it in GitHub Desktop.
Save Jonatthu/d9d7275aa928e4aa24ea2bd44e3aa11d to your computer and use it in GitHub Desktop.
Observer decorator for unsubscribe on ngOnDestroy - Angular 4
import { ISubscription } from 'rxjs/Subscription';
/**
* Subscription holder that will call ubsubscribe() function when ngOnDestroy
*/
export function Observer() {
return function logProperty(target: any, key: string) {
const observerKey = 'OB' + key;
const observerValue = 'observerSOD';
const originalOnDestroy = target.ngOnDestroy;
target.constructor.prototype[observerKey] = observerValue;
target.ngOnDestroy = function () {
originalOnDestroy();
for (const prop in this) {
const value: any = this[prop];
if (value == observerValue) {
const subscription: ISubscription = this[prop.replace('OB', '')];
subscription.unsubscribe();
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment