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);
}
)
}
)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With