I am after extending a Observables service to return data from local storage.
Scenario: Component will subscribe to Service.GetAll() and GetAll() will look up in the localStorage for data if found it will return else it will make a api call to get the data.
I managed to do this using Promise, but I prefer to convert it to Observables
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', activityScheduleFrequencies);
return ScheduleFrequencies || [];
})
.catch(this.handleError);
}
}
Appropriate if some one can show me how I can extend below service to do the same.
getAll(): Observable<TransactionStatus[]> {
return this.http.get(this.apiUrl)
.map(this.extractData)
.catch(this.handleError);
}
Thank you Asanka
Update Thank you @nzjun90 for the reply it works need to import 'of' import 'rxjs/add/observable/of';
let me know if you need clarification.
getAll(): Observable<TransactionStatus[]> {
let ScheduleFrequencies: IScheduleFrequency[] = this.storageService.get('ScheduleFrequencies');
if (ScheduleFrequencies != null) {
return Observable.of(ScheduleFrequencies);
}
return this.http.get(this.apiUrl)
.map((response)=>{
let ScheduleFrequencies: IScheduleFrequency[] = response.json();
this.storageService.save('ScheduleFrequencies', activityScheduleFrequencies);
return ScheduleFrequencies || [];
}).catch( e => {return this.handleError});
}