有2项服务:
-
DataService - 从服务器获取数据
-
CacheService - 订阅DataService并保存映射数据
和组件
- ComponentA - 注入CacheService并具有处理缓存数据的foo函数
我的问题是 - How do I ensure that my CacheService is done with data when my foo function gets called .
Current solution 我有点喜欢但不确定是否有更好的Angular 2方式 . 完成Rx.Observables
我的解决方案(代码简化):
export class CacheService {
myData: IData;
dataLoadedObservable: Observable;
private _emitter: any;
constructor(dataService: DataService){
this.dataLoaded = Observable.create(
e => {
_emitter = e;
});
}
private cacheData(){
this.dataService.loadData().subscribe(data => {
this.myData = data;
this._emitter.next('data loaded');
});
}
}
ComponentA
export class ComponentA {
this.cacheService.dataLoadedObservable.subscribe(
isLoaded => {
if(isLoaded === 'data loaded'){
// Now this.cacheService.myData is ready
}
}
);
}
1 回答
你可能应该像这样重构你的数据服务:
这个重构的目标是隐藏一个可观察的数据 .
一个简单的用法是:
在您从中发出数据(使用
next()
调用)之前,不会调用订阅,这意味着一旦您实际拥有数据,您的订阅就会被调用 .