Ionic 2/Angular 2 promise returning observable

后端 未结 4 1419
-上瘾入骨i
-上瘾入骨i 2021-02-15 02:46

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 i

4条回答
  •  灰色年华
    2021-02-15 02:52

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

提交回复
热议问题