【问题标题】:Wait for Localstorage then call api等待 Localstorage 然后调用 api
【发布时间】:2019-10-15 17:23:00
【问题描述】:

我从用户输入中获取设置并将其存储在本地存储中。我在 API 调用中使用这些数据。

 userlocation;
 userservice ;
 usercategory ;

 constructor(public http: HttpClient, public storage : Storage) { }

 getListings(){

 this.storage.get('area').then((userlocation) => {
  this.userlocation =  userlocation;

  console.log(this.userlocation)
 });

  this.storage.get('ser').then((userservice) => {
  this.userservice =  userservice;

  console.log(this.userlocation)
 });

  return  this.http.get(this.api_url+"?location="+ this.userlocation+ 
  "&ser= " + this.userservice)

 }

api调用在localstorage获取数据之前发生的问题。 如何让 API 调用等待本地存储

【问题讨论】:

  • 当你从 localStorage 获取不同的值时,为什么要使用相同的变量名??
  • 是的,这是我的问题,但我认为这不能解决问题

标签: api ionic-framework angular6 local-storage ionic4


【解决方案1】:

使用 async 和 await 你可以解决这个问题。

userlocation;
 userservice ;
 usercategory ;

 constructor(public http: HttpClient, public storage : Storage) { }

 async getListings(){ 

 await this.storage.get('area').then((userlocation) => {
  this.userlocation =  userlocation;

  console.log(this.userlocation);

    await this.storage.get('ser').then((userservice) => {
      this.userservice =  userservice;

      console.log(this.userlocation)
    });
 });



  return  this.http.get(this.api_url+"?location="+ this.userlocation+ 
  "&ser= " + this.userservice)

 }

【讨论】:

  • 我得到这个错误 'await' 表达式只允许在异步函数中。
  • 是的,请检查我的答案中的函数名称getLIstings()
  • 我通过从 localstorge 获取一个密钥来尝试它。 api调用没有发生。这是我的页面代码: this.AuthService.getListings().then(data => { console.log(data); this.items = data; });
  • 我不明白
  • API 调用未发生
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-29
  • 2021-05-05
  • 2014-05-06
  • 2019-10-13
  • 2018-08-03
  • 2019-08-16
相关资源
最近更新 更多