2017-05-25 19 views
0

状態をチェックしたい(データがストレージにあるか、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(); 
     } 
    ); 
} 
+0

これは私には見えません。悲しいことに、私はobservablesにはあまりよく似ていませんが、ここでのキーはsubscribeの論理if文の代わりにRxJsメソッドの1つにあると思います。リアクティブパターンを使用してこのケースを処理するものがなければなりません。 – cgTag

答えて

1

あなたはこのためmergeMapflatMapが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';

+1

ありがとう..私はRxJSについてもっと読む必要があります.. :) – Lyczos

関連する問題