Last active
November 9, 2018 14:00
-
-
Save WouterSpaak/c678d67b4cc27fc775a0c9a21878524f to your computer and use it in GitHub Desktop.
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 { HostListener } from '@angular/core'; | |
import { Subject, UnaryFunction, Observable } from 'rxjs'; | |
export function ObservableHostListener(): PropertyDecorator { | |
return (target: any, key: string) => { | |
// The stuff we did earlier ... | |
// Patch ngOnDestroy so we can correctly complete our subject. | |
patchOnDestroy(target, subject); | |
// Call our preparedDecorator with the target class and our super secret key, | |
// so Angular wires the event to our monkey patched method instead of our | |
// decorated key. | |
preparedDecorator(target, newKey); | |
} | |
} | |
function patchOnDestroy(target: any, subject: Subject<any>) { | |
const oldOnDestroy = target['ngOnDestroy'] || (() => undefined); | |
target['ngOnDestroy'] = () => { | |
subject.complete(); | |
oldOnDestroy(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment