如何在http请求中使用存储数据?

时间:2018-12-24 23:21:59

标签: javascript angular ionic-framework

我不能在另一个函数中使用“ ids”变量。始终返回未定义状态。我如何使用此变量。这对我来说很重要。因为我将在http请求中使用此变量。

    storageGet(){
        this.storage.get('favoriteStory').then((val) => {
                  this.ids = val;
                });
              }


    getStories() {
        return this.http.get("https://myaddress.com/funnies/"+this.ids+"/favorites/")
          .map(response => response.json())
      }

2 个答案:

答案 0 :(得分:0)

您可以使用switchMap()中的rxjs/operator

首先,您从存储中获取数据,并使用Promise方法将Observable转换为from。然后使用switchMap将结果映射到可观察的内部。

import {from} from 'rxjs';

import {switchMap} from 'rxjs/operators';


storageGet(){
    return this.storage.get('favoriteStory');
}


getStories(){
    return from(this.storageGet()).pipe(
      switchMap(storageVal =>this.http.get("https://myaddress.com/funnies/"+storageVal+"/favorites/")),
      map(response => response.json())
    )
}

然后您可以subscribegetStories()方法。

希望有帮助。

答案 1 :(得分:0)

storageGet(){
    // return a promise
    if(this.ids !== undefined) {
        return Promise.resolve(this.ids);
    }

    return this.storage.get('favoriteStory').then((val) => {
          this.ids = val;
          // return the value so that the next `then` in chain can have access to it
          return val;
    });
}


getStories() {
        return this.storageGet().then(ids => {          
           return this.http.get("https://myaddress.com/funnies/"+ids+"/favorites/")
              .map(response => response.json())
        })
}
相关问题