I have a service that maintains a context property
@Injectable()
export class MyService {
constructor(private _http: Http) {}
// a variable/getter in service that holds context
_currentContext: any;
get currentContext() { return this._currentContext;}
// a method in service that fetches context
fetchContext() {
return this._http.get(`/api/xxx`).map(response => response.json());
}
Now a component can inject this service, and elements in component template can directly bind to the context. These bindings get updated as part of change detection whenever context changes.
What if I want to do run some logic in component when context changes?
@Component({
selector: 'my-cmp',
template: `<div *ngIf="_myService.currentContext` >asdf</div>
})
export class MyComponent{
constructor(private _myService: MyService) {}
//doSomethingOnContextChange(){}
}
I believe the answer is to create/maintain an Observable in my service, and then my component subscribes to that observable.
_currentContextObservable= new Subject<any>();
get currentContextObservable(): Observable<any> { return this._currentContextObservable; }
So, for each such variable, do I need to maintain one variable/getter and one subject/observable? Or is there any other elegant/better way?