Typescript离子3异步/等待实现

时间:2017-04-28 19:49:45

标签: angular typescript ionic3

我目前面临一个问题,当UserData被注入到我的其他组件中时,Load()函数将始终比构造函数中的getFromStorageAsync()更早启动,因此ip_address始终是未定义的。

以下是我的服务代码(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);
        });
    });
  }
}

由于未定义的IP地址,无法从服务器获取数据。是使用async和等待的正确方法。请帮忙。谢谢!

1 个答案:

答案 0 :(得分:1)

let storage = await storage.ready();
let val =     await this.storage.get('ip_address');
this.ip_address = val.toPromise();