首页 文章

Angular 2 - 等待来自服务的数据init

提问于
浏览
1

有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 回答

  • 1

    你可能应该像这样重构你的数据服务:

    export class CacheService {
        private data$:Observable<IData>;
    
        constructor(private dataService: DataService){
            //We initialize the data Observable.
            this.data$ = new Subject();
            //We load initial data.
            this.dataService.loadData().subscribe(data => {
                //Once the data is loaded, we have to emit its value from our data$ observable.
                this.data$.next(data);
            });
        }
    
        //getter for our observable.
        public getData():Observable<IData>{
            return this.data$
        }
    
        //setter for data, hiding the observable logic behind.
        public setData(data:IData){
            this.data$.next(data);
        }
    }
    

    这个重构的目标是隐藏一个可观察的数据 .

    一个简单的用法是:

    cacheService.data.subscribe(data => console.log(data));
    

    在您从中发出数据(使用 next() 调用)之前,不会调用订阅,这意味着一旦您实际拥有数据,您的订阅就会被调用 .

相关问题