我想检查条件(数据是否在存储中可用或从api获取数据)为true / false,然后调用传递结果的相应函数。
现在,我正在组件中进行检查,但是我想将其移至服务端。
服务
getData() {
// check source of data to return...
return this.hasLocal().subscribe((res) => {
if (res === 0) // no data in storage
return this.getRemote(); // <-- I want to return this
else
return this.getLocal(); // <-- or this to the component.
})
}
getRemote() {
console.log('getRemote()');
return this.api.get(this.apiEndpoint).map(
res => {
let resJson = res.json();
// save data to storage:
this.storage.set(this.storageName, JSON.stringify(resJson))
.then(() => console.log('Data saved in storage.'))
.catch(() => console.warn('Error while saving data in storage.'));
return resJson;
});
}
getLocal() {
console.log('getLocal()');
let promise = this.storage.get(this.storageName).then(res => {
return res;
});
return Observable.fromPromise(promise).map(res => {
return JSON.parse(res);
});
}
hasLocal() {
let promise = this.storage.length().then(res => res);
return Observable.fromPromise(promise).map(res => res);
}
在组件中调用
GetData()
,然后将结果写入数组contacts
。component.ts
loadData() {
this.contactsProvider.getData().subscribe(
contacts => {
console.log(contacts);
this.initializeData(contacts);
this.loader.dismiss();
}
);
}
最佳答案
您可以为此使用mergeMap
(flatMap
是rxjs4别名)运算符:
getData() {
// check source of data to return...
return this.hasLocal().mergeMap((res) => {
if (res === 0) // no data in storage
return this.getRemote(); // <-- I want to return this
else
return this.getLocal(); // <-- or this to the component.
})
}
flatMap
文档:http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-mergeMap您可以使用
import 'rxjs/add/operator/mergeMap';
导入