【发布时间】:2019-08-01 20:34:11
【问题描述】:
在我的 ionic 应用程序中,我使用 isAuthenticated 方法检查用户是否已通过身份验证。
在isAuthenticated() 我检查存储中是否有有效的令牌。
如果访问令牌已过期,我会刷新令牌并再次返回新的访问令牌。
我的问题是当我尝试使用refreshToken 方法刷新令牌时,应用程序不会等到它完成,所以访问令牌将返回 null。
export class AuthService {
token: JwtToken;
isAuthenticated(): Promise<boolean> {
return this.getToken().then(token => {
return token != null;
});
}
getToken(): Promise<JwtToken> {
return this.storage.get('token').then(async (token: JwtToken) => {
if (token == null) {
return null;
}
const jwtHelper = new JwtHelperService();
if (jwtHelper.isTokenExpired(token.access_token)) {
console.log('1');
// I need wait until the function below finished
await this.refreshToken(token);
console.log('3');
// and then return refreshed access token
return this.token;
} else {
return token;
}
});
}
async refreshToken(token: JwtToken) {
console.log('2-1');
return await this.http.post('http://api.com/auth/refresh', {refresh_token: token.refresh_token}).subscribe(async (res: JwtToken) => {
console.log('2-2');
this.token = res;
await this.setToken(res);
console.log('2-3');
return this.token;
});
}
}
这是控制台输出:
1
2-1
3
2-2
2-3
当我需要它时
1
2-1
2-2
2-3
3
它以某种方式忽略了await refreshToken(token)...
【问题讨论】:
标签: angular ionic-framework ionic4