我在扩展Observables服务后从本地存储返回数据。
方案: 组件将订阅Service.GetAll()和GetAll()将在localStorage中查找数据,如果发现它将返回,否则它将进行api调用以获取数据。
我设法使用Promise,但我更喜欢将其转换为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);
}
}
如果有人可以告诉我如何延伸到服务以下来做同样的事情。
getAll(): Observable<TransactionStatus[]> {
return this.http.get(this.apiUrl)
.map(this.extractData)
.catch(this.handleError);
}
谢谢 Asanka
更新 谢谢@ nzjun90的回复工作需要导入'of' import'rxjs / add / observable / of';
答案 0 :(得分:5)
如果您需要澄清,请告诉我。
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});
}