У меня проблема с вызовом Http с данными, полученными из локального хранилища - PullRequest
0 голосов
/ 15 июня 2019

Я делаю запрос API для получения некоторых данных, зависит от пользовательской опции.Я получаю эту опцию пользователя и сохраняю ее в локальном хранилище, чтобы получить ее в службе API, чтобы использовать ее в качестве параметра в URL.
Моя проблема заключается в том, что эти запросы работают правильно только в первом.когда пользователь переходит назад и выбирает другой вариант, служба получает старые данные из локального хранилища, а не обновленные данные.Как я могу решить эту проблему.

Я пытаюсь очистить локальное хранилище после завершения вызова, но это не работает

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

this.storage.get('cat').then((usercategory) => {
  this.usercategory =  usercategory;
  console.log(this.usercategory)
 });

 this.storage.get('loc').then((userlocation) => {
  this.userlocation =  userlocation;
  console.log(this.userlocation)

 });

 this.storage.get('serv').then((userservice) => {
  this.userservice =  userservice;
  console.log(this.userservice)

 });

getdata(){

return this.http.get(this.url + "&location=" + this.userlocation + 
"&price=" + this.usercategory + "&service=" + this.userservice);

}

Ответы [ 3 ]

0 голосов
/ 16 июня 2019

Я решил проблему, получив значения из localStorage в компоненте страницы и передав его в службу API.

             constructor(private AuthService: DubaiService, 
public loadingController: LoadingController,
public storage: Storage,
 private SettingsAuth :SettingsService,
 public modalController: ModalController) {

this.showLoader()


   Promise.all([this.storage.get("cat"),
   this.storage.get("loc"),
   this.storage.get("serv")]).t hen(values => {
  this.usercategory = values[0];
  this.userlocation = values[1];
  this.userservice = values[2];
  console.log(values)
  })
}


 ionViewDidEnter(){

this.AuthService.getListings(this.usercategory,this.userlocation,this.userservice)
 .subscribe((data) => {
  console.log(data);
  this.listing_items = data, 
  err => console.log(err);
  this.hideLoader()
  ,
  () =>  console.log("done");
   this.hideLoader();
   });



   }

и метод My API Call:

            getListings(usercategory,userlocation,userservice){

           return this.http.get(this.url + "&location=" + userlocation + 
           "&price=" + usercategory + "&service=" + userservice);

            }
0 голосов
/ 17 июня 2019

Получение значений из локального хранилища выполняется асинхронно. Поэтому вам нужно дождаться этих значений, прежде чем использовать их как:

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

async getlocalstorage(){

  await this.storage.get('cat').then((usercategory) => {
  this.usercategory =  usercategory;
  console.log(this.usercategory)
 });

 await this.storage.get('loc').then((userlocation) => {
  this.userlocation =  userlocation;
  console.log(this.userlocation)

 });

 await this.storage.get('serv').then((userservice) => {
  this.userservice =  userservice;
  console.log(this.userservice)

 });
}
0 голосов
/ 15 июня 2019

Похоже, вы обновляете свойства конструктора класса обслуживания, и он вызывается только при создании экземпляра службы.

Вы можете создать функцию для получения значений и вызывать эту функцию всякий раз, когда вы делаете вызов API, таким образом, свойства будут обновляться каждый раз, когда вы вызываете API.

И не забудьте поместить только тот код в конструктор, который должен инициализировать свойства класса или должен вызываться только один раз во время создания экземпляра.

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

getlocalstorage(){

  this.storage.get('cat').then((usercategory) => {
  this.usercategory =  usercategory;
  console.log(this.usercategory)
 });

 this.storage.get('loc').then((userlocation) => {
  this.userlocation =  userlocation;
  console.log(this.userlocation)

 });

 this.storage.get('serv').then((userservice) => {
  this.userservice =  userservice;
  console.log(this.userservice)

 });
}


getdata(){
getlocalstorage();
return this.http.get(this.url + "&location=" + this.userlocation + 
"&price=" + this.usercategory + "&service=" + this.userservice);

}
...