Search code examples
angularlazy-loadingobservableangular2-servicesangular-services

Angular 2 - Wait for data init from service


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

Solution

  • 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.