我有一个共享服务(从开始这个建议),该高速缓冲存储器,并返回第一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请求,而不是返回缓存的数据。有人可以建议我如何避免这种副作用吗?
您的解决方案无法涵盖所有情况。
将其与我从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(...)
技术原因。他们认为它更具可维护性。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句