![](/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.