简体   繁体   English

检查Observable的条件并执行/返回函数(angular2,rxjs)

[英]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. 我想检查条件(数据是否在存储中可用或从api获取数据)为true / false,然后调用传递结果的相应函数。

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 array contacts . 在组件中调用GetData() ,然后将结果写入数组contacts

component.ts component.ts

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

You can use the mergeMap ( flatMap is the rxjs4 alias) operator for this: 您可以mergeMap使用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 documentation: http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-mergeMap flatMap文档: http : flatMap

You can import it with import 'rxjs/add/operator/mergeMap'; 您可以使用import 'rxjs/add/operator/mergeMap';导入它import 'rxjs/add/operator/mergeMap';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM