Menu

Extending Angular 2 Promise based service to return data from local Storage.

I have also converted this to a Observables service in this blog post, until then will work as a Promise based service.

Every day we deal with lot of data, some of the data will remain same for years. For example – list of States in Australia. Easy to maintain this data on server side rather than hard codeing it on client side – I am sure you will agree. I have utilised the local Storage to save data on client side, but if data not found it will make a server call to get the data and return them to caller. Belwo is the Angular 2 Service.

getAll(): Promise<IScheduleFrequency[]> {
   let scheduleFrequencies: IScheduleFrequency[] = this.storageService.get('scheduleFrequencies');
   if (scheduleFrequencies != null) {
     return Promise.resolve(scheduleFrequencies);
   } else {
     return this.http.get(this.apiUrl)
            .toPromise()
             .then((response) => {
                    let scheduleFrequencies: IScheduleFrequency[] = response.json();
                    this.storageService.save('scheduleFrequencies', scheduleFrequencies);
                    return scheduleFrequencies || [];
                })
                .catch(this.handleError);
   }
}

Your component can have below code to get the data, prefer to do it in the service level rather than in the component.

getFrequencies() {      
   return this.scheduleFrequencyService.getAll()
      .then((returnData: IScheduleFrequency[]) => {
         this.scheduleFrequencies = returnData; 
      },
      error => {
      // Show error
      });
}

 

Leave a comment