首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >角等待订阅完成,然后返回

角等待订阅完成,然后返回
EN

Stack Overflow用户
提问于 2019-03-11 13:52:44
回答 2查看 482关注 0票数 0

在我的离子型应用程序中,我检查用户是否通过了身份验证,或者没有使用isAuthenticated方法。

isAuthenticated()中,我检查存储中是否存在有效的令牌。

如果访问令牌过期,则刷新令牌,并再次返回新的访问令牌。

我的问题是,当我尝试使用refreshToken方法刷新令牌时,app不会等到完成时才返回访问令牌。

代码语言:javascript
运行
复制
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;
        });
    }
}

这是控制台输出:

代码语言:javascript
运行
复制
1
2-1
3
2-2
2-3

当我需要它时

代码语言:javascript
运行
复制
1
2-1
2-2
2-3
3

它忽略了await refreshToken(token) ..。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-03-12 06:16:31

这个question帮助我解决了我的问题。

我像这样改变了refreshToken

代码语言:javascript
运行
复制
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();
        });
    });
}
票数 0
EN

Stack Overflow用户

发布于 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;);}

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55103381

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档