Search code examples
javascriptangularionic-frameworkionic3ionic-storage

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

Solution

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