2016-04-14 53 views
3

我已經共享服務(從this建議開始)該高速緩存,並返回第一HTTP請求後一些數據:角2,併發在共享服務的HTTP觀察到

export class SharedService { 
    constructor(private http:Http) { 
    } 

    getData() { 
    if (this.cachedData) { 
     return Observable.of(this.cachedData); 
    } else { 
     return this.http.get(...) 
      .map(res => res.json()) 
      .do((data) => { 
       this.cachedData = data; 
      }); 
    } 
    } 
} 

我的問題是我有一些指令和同一模板中的所有組件同時進行初始化,並且每個組件都同時調用(在ngInit函數內部)getData方法(所有這些方法都在第一個成功之前),因此服務啓動許多http請求而不是返回緩存的數據。 有人可以建議我如何避免這種副作用?

回答

2

您的解決方案不涵蓋所有情況。

比較它我的方法從https://stackoverflow.com/a/36291681/217408

getData() { 
    if(this.data) { 
     // if `data` is available just return it as `Observable` 
     return Observable.of(this.data); 
    else if(this.observable) { 
     // if `this.observable` is set then the request is in progress 
     // return the `Observable` for the ongoing request 
     return this.observable; 
    } else { 
     // create the request, store the `Observable` for subsequent subscribers 
     this.observable = this.http.get('/someUrl') 
      .map(res => res.json()) 
      .do(val => { 
      this.data = val; 
      // when the cached data is available we don't need the `Observable` reference anymore 
      this.observable = null; 
      }) 
      // make it shared so more than one subscriber can get the result 
      .share(); 
     return this.observable; 
    } 
} 

直到請求至今未歸,你需要返回從第一次請求後續請求,直到完成了第一個請求創建Observable

https://stackoverflow.com/a/36296015/217408也顯示和有趣的方法,但與小(取決於您的要求)的缺點,請求無法取消。

此外,確保您已經像@MichaelD解釋過的那樣只提供一次註冊您的共享服務。

Angular團隊建議使用根組件的providers: [...]列表而不是bootstrap(...),但沒有技術原因。他們認爲它更容易維護。

+1

非常感謝Günter,回覆「等待觀察」解決我的問題。 –

+0

太好了,謝謝你的反饋:) –

1

你必須在引導方法聲明爲您服務:

bootstrap(AppComponent, [SharedService]); 

這項服務將只有一次(單身),實例化,所以應該解決您的問題。