2017-05-25 2 views
0

Ich möchte die Bedingung überprüfen (ist Daten im Speicher verfügbar oder erhalten Daten von API) ist wahr/falsch und rufen Sie dann die entsprechende Funktion, die das Ergebnis ist weitergegeben.Überprüfen der Bedingung der Observable und Ausführen/Zurückgeben Funktion (angular2, rxjs)

Jetzt überprüfe ich dies in der Komponente, aber ich möchte dies auf die Service-Seite verschieben.

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() wird in der Komponente genannt wird, und dann wird das Ergebnis auf dem Array contacts geschrieben.

component.ts

loadData() { 
    this.contactsProvider.getData().subscribe(
     contacts => { 
      console.log(contacts); 
      this.initializeData(contacts); 
      this.loader.dismiss(); 
     } 
    ); 
} 
+0

Das sieht nicht richtig für mich. Leider bin ich nicht sehr gut bei Observablen, aber ich denke, der Schlüssel hier ist eine der RxJs-Methoden anstelle einer logischen if-Anweisung in subscribe. Es muss etwas geben, das diesen Fall mit dem reaktiven Muster behandelt. – cgTag

Antwort

1

Sie die mergeMap (flatMap ist der rxjs4 alias) Operator für diese verwenden:

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 Dokumentation: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-mergeMap

Sie importieren es mit import 'rxjs/add/operator/mergeMap';

+1

Vielen Dank .. :) Ich muss mehr über RxJS lesen .. :) – Lyczos

Verwandte Themen