Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
Typescript ionic 3 async / await implementation

I'm currently facing an issue, when the UserData is injected into my other component, the Load() function will always started earlier than the getFromStorageAsync() within the constructor, so ip_address is always undefined.

the below is my service code (UserData)

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Storage } from '@ionic/storage';
import 'rxjs/add/operator/map';

/*
  Generated class for the UserData provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class UserData {
  public data: any;
  private ip_address: any;

  constructor(public http: Http, private storage: Storage) {
    this.data = null;
    this.ip_address = this.getFromStorageAsync()
  }

  async getFromStorageAsync(){
        let val = await this.storage.get('ip_address');
        this.ip_address = val.toPromise();
    }

  load(): any {
    console.log(this.ip_address);
    if (this.data) {
      return Promise.resolve(this.data);
    }
    return new Promise(resolve => {
      this.http.get(this.ip_address + "/api/user")
        .map(res => res.json())
        .subscribe(data => {
          this.data = data;
          resolve(this.data);
        });
    });
  }
}

it failed to fetch data from server due to undefined ip address. is it correct way to use async and await. please help. thanks !

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

let storage = await storage.ready();
let val =     await this.storage.get('ip_address');
this.ip_address = val.toPromise();
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda