状態をチェックしたい(データがストレージにあるか、apiからデータを得るか)をtrue/falseにして、結果が対応する関数を呼び出したい渡される。Observableの状態をチェックし、実行/戻り関数(angular2、rxjs)
ここでコンポーネントでこれをチェックしていますが、これをサービス側に移動したいと思います。
service.ts
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();
}
);
}
これは私には見えません。悲しいことに、私はobservablesにはあまりよく似ていませんが、ここでのキーはsubscribeの論理if文の代わりにRxJsメソッドの1つにあると思います。リアクティブパターンを使用してこのケースを処理するものがなければなりません。 – cgTag