Created
January 4, 2018 18:15
-
-
Save Jonatthu/d9d7275aa928e4aa24ea2bd44e3aa11d to your computer and use it in GitHub Desktop.
Observer decorator for unsubscribe on ngOnDestroy - Angular 4
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 { 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