Ionic 2/Angular 2 promise returning observable

爱⌒轻易说出口 提交于 2019-12-09 10:36:47

问题


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

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!


回答1:


Here's what you can do:

Your code below

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

changes to

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:


In angular 2, the Http service functions (get, post, etc.) return an Observable object. This is just the way they implemented it.

If you're used to promises, and want your service to return a promise instead, you can use the toPromise function that's built in Observable objects.

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

And then

this.tokenService.loadStuff().then(data => {
    data = data.json(); //you might need to do that, depending on the structure of the response
    this.storage.set('stuff', data);
    return data;
});    



回答3:


I got it to work using a combination of Observable.fromPromise() and .flatMap():

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

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

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

You'll also need to add these imports:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/observable/fromPromise';
import 'rxjs/add/operator/mergeMap';



回答4:


Use ' Observable.fromPromise ' to convert promise to observable.



来源:https://stackoverflow.com/questions/37994343/ionic-2-angular-2-promise-returning-observable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!