Skip to content

Instantly share code, notes, and snippets.

@WouterSpaak
Last active November 9, 2018 14:00
Show Gist options
  • Save WouterSpaak/c678d67b4cc27fc775a0c9a21878524f to your computer and use it in GitHub Desktop.
Save WouterSpaak/c678d67b4cc27fc775a0c9a21878524f to your computer and use it in GitHub Desktop.
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