简体   繁体   中英

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

I'm trying to get data from the server using token from ionic storage. The problem I'm experiencing is when the get token promise can't retrieve the token on time. Therefore, whenever I reload or reopen the app it sometimes return with an unauthorized error.

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

You can return a promise from getToken then execute 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
    })
}
});
}

In your page

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM