angular 等待订阅完成,然后 return

angular wait for subscription finishes and then return

在我的 ionic 应用程序中,我使用 isAuthenticated 方法检查用户是否已通过身份验证。
isAuthenticated() 我检查存储中是否有有效令牌。
如果访问令牌已过期,我会刷新令牌并再次 return 新的访问令牌。
我的问题是当我尝试使用 refreshToken 方法刷新令牌时,应用程序不会等到它完成所以访问令牌将 returned 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)...

解决方案是使用async,像这样等待: 如果你想调用函数 refereshToken : let result= await refereshToken(argument) ; 以及 refereshToken 原型的功能你应该这样写: 异步刷新令牌(令牌:JwtToken){ return this.http.post('http://api.com/auth/refresh', {refresh_token: token.refresh_token}).subscribe(async (res: JwtToken) => { this.token = 水库; 等待this.setToken(res); return this.token; }); }

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

我把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();
        });
    });
}