Lyczos
Lyczos

Reputation: 316

Check condition of Observable and execute/return function (angular2, rxjs)

I want to check the condition (is data is available in storage or get data from api) is true/false and then call the corresponding function which the result is passed on.

Now, i'm checking this in the component but I want to move this to the service side.

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() is called in the component, and then the result is written to the arraycontacts.

component.ts

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

Upvotes: 0

Views: 1736

Answers (1)

eko
eko

Reputation: 40647

You can use the mergeMap( flatMap is the rxjs4 alias) operator for this:

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

You can import it with import 'rxjs/add/operator/mergeMap';

Upvotes: 1

Related Questions