I have two Angular2 components which need to share data via a service:
@Injectable() export class SearchService { private searchResultSource = new Subject<string>() searchResult$ = this.searchResultSource.asObservable() setSearchResults(_searchResult: string): void { this.searchResultSource.next(_searchResult) } }
Suppose ComponentA
is rendered and it emits an event via SearchService.setSearchResults
. Then the user navigates to ComponentB
, which also subscribes to searchResult$
. However, ComponentB
will never observe the event emitted by ComponentA
because it was not subscribed to searchResult$
at the time ComponentA
emitted an event, as it did not exist.
How can I create an Observable
which emits the last event to every new subscriber?
There are two ways to get this last emited value. You can either get the value by accessing the . value property on the BehaviorSubject or you can subscribe to it. If you subscribe to it, the BehaviorSubject will directly emit the current value to the subscriber.
Rather than a standard subject (Observable) that just emits values as they come in, a BehaviorSubject emits the last value upon subscribe() . You can also get the last value manually using the BehaviorSubjects getValue() method.
To get current value of RxJS Subject or Observable, we can use the first method. const observable = of("foo"); const hasValue = (value: any) => { return value !== null && value !== undefined; }; const getValue = <T>(observable: Observable<T>): Promise<T> => { return observable.
So the only solution that I found to get the value of a BehaviorSubject was: let value; myBehaviorSubject. take(1). subscribe( (e) => value = e );
BehaviorSubject
immediately emits the last value to new subscribers:
@Injectable() export class SearchService { private searchResultSource = new BehaviorSubject<string>(''); setSearchResults(_searchResult: string): void { this.searchResultSource.next(_searchResult); } }
ReplaySubject
emits all previous events to new subscribers.
You can use the ReplaySubject to always get the last value of the Observer, something like this :
@Injectable() export class SearchService { private searchResultSource = new ReplaySubject<string>(1); setSearchResults(_searchResult: string): void { this.searchResultSource.next(_searchResult); } }
And just subscribe as normal.
A more advanced example can be found here : caching results with angular2 http service
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With