How to get last value when subscribing to an Observable?

后端 未结 2 1989
既然无缘
既然无缘 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(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

提交回复
热议问题