How to get last value when subscribing to an Observable?

后端 未结 2 1990
既然无缘
既然无缘 2020-12-28 14:12

I have two Angular2 components which need to share data via a service:

@Injectable()
export class SearchService {
           


        
相关标签:
2条回答
  • 2020-12-28 14:41

    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

    0 讨论(0)
  • 2020-12-28 14:49

    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.

    0 讨论(0)
提交回复
热议问题