Mas*_*ani 5 concurrency service caching angular
I have a shared service (starting from this suggestion) that cache and returns some data after first http request:
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;
});
}
}
}
Run Code Online (Sandbox Code Playgroud)
My problem is that I have some directives and components inside the same template that are all initialized at the same time and each one call simultaneously (inside ngInit function) the getData method (all of them before the first one succeeded) and so the service starts many http requests instead of returning cached data. Can someone suggest me how to avoid this side effect?
您的解决方案并不能涵盖所有情况。
将其与我的方法进行比较/sf/answers/2540417701/
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;
}
}
Run Code Online (Sandbox Code Playgroud)
在请求没有返回之前,您需要将从Observable第一个请求创建的内容返回到后续请求,直到第一个请求完成。
/sf/answers/2540721081/也显示了有趣的方法,但有一个小(取决于您的要求)缺点,即请求无法取消。
还要确保您作为提供商仅注册一次共享服务,如 @MichaelD 所解释的那样。
Angular 团队建议使用providers: [...]根组件列表来代替bootstrap(...),但没有技术原因。他们认为它更易于维护。
| 归档时间: |
|
| 查看次数: |
1171 次 |
| 最近记录: |