【问题标题】:angular wait for subscription finishes and then return角等待订阅完成然后返回
【发布时间】: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


【解决方案1】:

解决方案是使用异步,等待如下: 如果你想调用一个函数 refereshToken : 让结果=等待refereshToken(参数); 和refereshToken原型的功能你应该这样写: 异步刷新令牌(令牌:JwtToken){ return this.http.post('http://api.com/auth/refresh', {refresh_token: token.refresh_token}).subscribe(async (res: JwtToken) => { this.token = res; 等待 this.setToken(res); 返回这个.token; }); }

【讨论】:

    【解决方案2】:

    这个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();
            });
        });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-16
      • 1970-01-01
      相关资源
      最近更新 更多