首页 > 解决方案 > 等待 Localstorage 然后调用 api

问题描述

我从用户输入中获取设置并将其存储在本地存储中。我在 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

标签: apiionic-frameworkangular6local-storageionic4

解决方案


使用 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)

 }

推荐阅读