![](/img/trans.png)
[英]Angular2 RxJS getting 'Observable_1.Observable.fromEvent is not a function' error
[英]Check condition of Observable and execute/return function (angular2, rxjs)
我想检查条件(数据是否在存储中可用或从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
使用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 : flatMap
您可以使用import 'rxjs/add/operator/mergeMap';
导入它import 'rxjs/add/operator/mergeMap';
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.