Ionic 3等待存储承诺在运行功能之前完全完成

时间:2018-03-07 11:39:00

标签: javascript angular ionic-framework ionic3 ionic-storage

我正在尝试使用离子存储中的令牌从服务器获取数据。我遇到的问题是get token promise无法按时检索令牌。因此,每当我重新加载或重新打开应用程序时,它有时会返回未经授权的错误。

仪表板service.ts

authUrl = "https://sampleapi.herokuapp.com"
authHeaders;

getToken() {
this.storage.get('token').then((token) => {
  console.log('Bearer ' + token);
  this.authHeaders = {
    headers: new HttpHeaders({
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + token
    })
}
});
}

getInfo(): Observable<Info> {
return this.http.get<Info>(this.authUrl + '/api/users/info', this.authHeaders).pipe(
  catchError(this.handleError)
);
}

dashboard.ts

ionViewDidLoad() {
this._dashboardService.getToken();
this._dashboardService.getInfo().subscribe(
  info => {
    console.log('USER INFO: ' + info);
    this.info = info
  },
  error => {
    console.log('INFO ERROR: ' + error);
  }
);
}

1 个答案:

答案 0 :(得分:4)

您可以从getToken返回一个promise,然后执行getInfo

getToken() {
return this.storage.get('token').then((token) => {
  console.log('Bearer ' + token);
  this.authHeaders = {
    headers: new HttpHeaders({
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Bearer ' + token
    })
}
});
}

在您的信息页

 ionViewDidLoad() {
    this._dashboardService.getToken().then(_=> {
    this._dashboardService.getInfo().subscribe(
      info => {
        console.log('USER INFO: ' + info);
        this.info = info
      },
      error => {
        console.log('INFO ERROR: ' + error);
      }
    )
}
)
    }
相关问题