5

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

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

仪表板.ts

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

1 回答 1

4

您可以从 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);
      }
    )
}
)
    }
于 2018-03-07T22:20:40.013 回答