I have two Angular2 components which need to share data via a service:
@Injectable()
export class SearchService {
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
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.