Angular 2 - Wait for data init from service

拈花ヽ惹草 提交于 2019-12-24 09:35:25

问题


There are 2 services:

  • DataService - gets data from the server
  • CacheService - subscribes to DataService and holds mapped data

and component

  • ComponentA - Injects CacheService and has foo function that handles cached data

My question is - How do I ensure that my CacheService is done with data when my foo function gets called.

Current solution that I kinda like but am not sure if there isn't some better Angular 2 way. Done with Rx.Observables

My solution (Code is simplified):

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:


You should probably refactor your data service like this:

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

The goal behind this refactor is to hide your data behind an observable.

A simple usage would be:

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

The subscription will not get called before you emit data from it (using next() call), meaning that your subscription will get called once you actually have data.



来源:https://stackoverflow.com/questions/44050670/angular-2-wait-for-data-init-from-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!