2017-02-20 34 views

回答

2

這個答案是指RxJS 5

一種方法是使用publishReplay

this.http 
    .get() 
    .map() 
    .publishReplay(1) 
    .refCount(); 

如果源是源,即完成(這是典型的休息呼叫,因爲它在收到響應後完成),你也可以使用publishLast

this.http 
    .get() 
    .map() 
    .publishLast() 
    .refCount(); 

而第三種方式(它給你最大的靈活性)將使用外部BehaviorSubjectReplaySubject

public myData$: BehaviorSubject<any> = new BehaviorSubject(null); // initial value is "null" 

public requestData(): BehaviorSubject<any> { 
    this.http 
     .get() 
     .map() 
     .do(data => this.myData$.next(data)) 
     .subscribe(); 

    return this.myData$.skip(1); // the returned subject skips 1, because this would be the current value - of course the skip is optional and depends on the implementation of the requesting component 
} 

在你的份(S),你可以通過myData$.subscribe(...)獲取當前「緩存」數據的數據或通過requestData().subscribe(...)獲取最新數據的數據。