离子2/角2承诺返回可观察 [英] Ionic 2/Angular 2 promise returning observable

查看:55
本文介绍了离子2/角2承诺返回可观察的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到一种情况,我需要从Ionic 2应用程序中的存储中获取一条数据,然后使用该数据创建HTTP请求.我遇到的问题是SqlStorage方法返回promise,而http meth返回一个observables.我必须要做这样的事情才能使其正常工作:

I have a situation where I need to fetch a piece of data from storage in an Ionic 2 application and then use that data to create an HTTP request. The problem that I am running into is that the SqlStorage methods return promises and the http meth returns an observables. I'm having to do something like this to get it to work:

 getToken() {
    return this.storage.get('token').then((token) => {
        this.token = token;
        return token;
    });
 }

 loadStuff(){
    return this.tokenService.getToken().then(token => {
      return this.http.get("https://www.urltodatasource.com/api/v1/Endpoint?access_token="+token).map(res => res.json());
    });
  }

然后执行以下操作使其正常工作:

and then doing something like this to get it to work:

this.tokenService.loadStuff().then(observable => {
    observable.subscribe(data => {
         this.storage.set('stuff', data);
         return data;
    });
})

我一般对Angular和Ionic还是陌生的,所以我觉得有一种更好的方法来完成我想做的事情,但是我只是不知道怎么做.另外,关于可观测对象的所有可用资源很快变得非常复杂非常,这使像我这样的印象深刻的年轻开发人员非常困惑.

I'm very new to Angular and Ionic in general, so I feel like there is a much better way to accomplish what I'm trying to do, but I just don't know how. Also, all of the available resources out there about observables get very complicated very quickly which leaves an impressionable young developer like me very confused.

任何人都可以阐明如何更好地做到这一点吗?谢谢!

Can anyone shed some light on how to do this any better? Thanks!

推荐答案

您可以执行以下操作:

您的下面的代码

 getToken() {
    return this.storage.get('token').then((token) => {
        this.token = token;
        return token;
    });
 }

更改为

getToken: Observable<any> = 
    Observable.fromPromise(this.storage.get('token').then(token => {
    //maybe some processing logic like JSON.parse(token)
    return token;
}));

然后,您可以像在其他任何可观察对象中一样在组件中使用它.

Then in your component you can consume it like would any other observable.

this.serviceClass.getToken.subscribe(token => { 
//whatever you want to with the token
});

这篇关于离子2/角2承诺返回可观察的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆