Angular 2 - Binding with a subscription
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());
}
The component can now inject this service, and items in the component template can bind directly to the context . These bindings are updated as part of change detection when the context changes.
What if I want to execute some logic in a component when the 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 the 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 object / observable? Or is there some other elegant / better way?
source to share
I often use BehaviorSubject
for this type of service:
export class MyService { private contextSubject = new BehaviorSubject<any>(null); context$ = this.contextSubject.asObservable(); get context() { return this.contextSubject.value; } ... }
you can use either context
or context$
whichever you need.
source to share