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

Ionic 3 Wait for storage promise to completely finish before running function

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

仪表板-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);
  }
);
}

您可以 return 来自 getToken 的承诺然后执行 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);
      }
    )
}
)
    }