Reputation: 1803
TL;DR:
https://plnkr.co/edit/QP5skRU1MJ3ZoOtlA15I?p=preview
Why would you use a service's local variable over a subscription to an observable within that service?
Example of why it's confusing:
In the plunk, you'll see I have two components and a service. Those two components share an Observable which lives in that service.
In the service, I update a public variable and push that value to the observers.
This is the piece of code that seems redundant to me, but I see it all over in Angular2 tutorials.
src/number.ts
this.num = {
num: new Date().getTime()
};
this.observer.next(this.num);
Why would I do one or the other? I prefer the subscription method, but they seem to do the same thing. What am I missing?
NOTE: The setInterval and NgZone junk is only there for demonstration purposes. In real life, this data would come from HTTP, which would update the variable and/or push to the subscribers. Because I just grabbed the time every second, I also had to use NgZone.
Upvotes: 1
Views: 1127
Reputation: 657731
I guess what this is about is that with an Observable
you only get a value when an event is emitted but often you want the last (current) value immediately and later on being notfied about updates.
You can use a BehaviorSubject
that immediately emits the last emitted value again to new subscribers, or if you are less familiar with Rx you would probably use the pattern mentioned in your question. This allows you to
this.prop = this.service.num; this.service.observable.subscribe(val => this.prop = val);
to get the last value immediately and updates when they occur using from the observable.
Upvotes: 1