【问题标题】:Ionic 3 Wait for storage promise to completely finish before running functionIonic 3 在运行功能之前等待存储承诺完全完成
【发布时间】:2018-08-15 12:02:29
【问题描述】:

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

dashboard-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);
  }
);
}

【问题讨论】:

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


【解决方案1】:

你可以从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);
      }
    )
}
)
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-08
    • 1970-01-01
    • 2017-06-17
    • 1970-01-01
    • 2021-01-23
    • 2019-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多