Ren*_*ola 5 javascript ionic-framework ionic3 angular ionic-storage
我正在尝试使用离子存储中的令牌从服务器获取数据。我遇到的问题是,获取令牌承诺不能按时检索令牌。因此,每当我重新加载或重新打开该应用程序时,有时都会返回未经授权的错误。
仪表板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)
);
}
Run Code Online (Sandbox Code Playgroud)
仪表板
ionViewDidLoad() {
this._dashboardService.getToken();
this._dashboardService.getInfo().subscribe(
info => {
console.log('USER INFO: ' + info);
this.info = info
},
error => {
console.log('INFO ERROR: ' + error);
}
);
}
Run Code Online (Sandbox Code Playgroud)
您可以从 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
})
}
});
}
Run Code Online (Sandbox Code Playgroud)
在您的页面中
ionViewDidLoad() {
this._dashboardService.getToken().then(_=> {
this._dashboardService.getInfo().subscribe(
info => {
console.log('USER INFO: ' + info);
this.info = info
},
error => {
console.log('INFO ERROR: ' + error);
}
)
}
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2564 次 |
| 最近记录: |