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?
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.