在我的离子型应用程序中,我检查用户是否通过了身份验证,或者没有使用isAuthenticated
方法。
在isAuthenticated()
中,我检查存储中是否存在有效的令牌。
如果访问令牌过期,则刷新令牌,并再次返回新的访问令牌。
我的问题是,当我尝试使用refreshToken
方法刷新令牌时,app不会等到完成时才返回访问令牌。
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)
..。
发布于 2019-03-12 06:16:31
这个question帮助我解决了我的问题。
我像这样改变了refreshToken
:
refreshToken(token: JwtToken) {
return new Promise(resolve => {
this.http.post('http://api.com/auth/refresh', {refresh_token: token.refresh_token}).subscribe(async (res: JwtToken) => {
this.token = res;
await this.setToken(res);
resolve();
});
});
}
发布于 2019-03-11 20:52:58
解决方案是使用异步,这样等待:如果您想调用一个函数refereshToken :让result=等待refereshToken(参数);引用token的原型的功能应该是这样的:异步refreshToken(令牌: JwtToken) {返回this.http.post('http://api.com/auth/refresh',{refresh_token: token.refresh_token}).subscribe(异步(res: JwtToken) => { this.token = res;等待this.setToken(res);返回this.token;);}
https://stackoverflow.com/questions/55103381
复制相似问题