Skip to content

Instantly share code, notes, and snippets.

@amcdnl
Created February 20, 2018 05:09
Show Gist options
  • Save amcdnl/9795a413f9df006e92afa50190a446fe to your computer and use it in GitHub Desktop.
Save amcdnl/9795a413f9df006e92afa50190a446fe to your computer and use it in GitHub Desktop.
import { Input } from '@angular/core';
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
export function InputObservable<T>(inputName?: string) {
return (target: object, name: string): void => {
const subject = new BehaviorSubject(this[name]);
if (delete target[name]) {
Object.defineProperty(target, name, {
set(value: T): void {
subject.next(value);
},
get(): BehaviorSubject<T> {
return subject;
},
});
}
Input(inputName)(target, name);
};
}
@SanderElias
Copy link

Clever!
I would replace return subject; with return subject.asObservable(); so you don't 'leak' the subject into your class.
Perhaps even pipe in a distictUntillChanged to prevent repeated invocations that might occur.

@NetanelBasal
Copy link

NetanelBasal commented Feb 20, 2018

Nice! unfortunately, it will not work. When you initiate the BehaviorSubject the this context is not what you think it is, it's undefined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment