我已經共享服務(從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請求而不是返回緩存的數據。 有人可以建議我如何避免這種副作用?
非常感謝Günter,回覆「等待觀察」解決我的問題。 –
太好了,謝謝你的反饋:) –