Angular 2 - 等待服务初始化数据

Angular 2 - Wait for data init from service

有 2 项服务:

和组件

我的问题是 - 当我的 foo 函数 被调用时,如何确保我的 CacheService 完成数据处理

我有点喜欢的当前解决方案,但不确定是否有更好的 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');
        });
    }
}

组件A

export class ComponentA {
    this.cacheService.dataLoadedObservable.subscribe(
            isLoaded => {
                if(isLoaded === 'data loaded'){
                    // Now this.cacheService.myData is ready
                }
            }
        );
}

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

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);
    }
}

此重构背后的目标是将您的数据隐藏在 observable 后面。

一个简单的用法是:

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

订阅在您从订阅发出数据之前不会被调用(使用 next() 调用),这意味着您的订阅将在您实际拥有数据后被调用。