Ionic 2/Angular 2 承诺返回 observable [英] Ionic 2/Angular 2 promise returning observable

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

问题描述

我有一种情况,我需要从 Ionic 2 应用程序的存储中获取一段数据,然后使用该数据创建一个 HTTP 请求.我遇到的问题是 SqlStorage 方法返回承诺,而 http 方法返回一个 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 很陌生,所以我觉得有更好的方法来完成我想要做的事情,但我不知道该怎么做.此外,所有关于 observables 的可用资源都很快变得非常复杂非常,这让像我这样易受影响的年轻开发人员非常困惑.

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;
}));

然后在您的组件中,您可以像使用任何其他 observable 一样使用它.

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
});

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

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