How to get last value when subscribing to an Obser

2019-03-14 10:43发布

问题:

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?

回答1:

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.



回答2:

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