首页 > 解决方案 > 使 Angular 函数等待订阅完成

问题描述

我有一个 Angular 函数,我试图通过将用户的凭据与数据库进行比较来测试用户是否有效:

isLoggedIn() {
    this.userService.getUser(this.user.userName)
        .pipe(first())
        .subscribe(
            result => {
                this.currentUser = result;
                if (this.currentUser.fullName != result.fullName) {
                    return false
                }
                return true;
            },
            () => { });

    console.log('The function shouldn't go here')      
}

如何让该功能等待我的订阅完成?现在它直接进入 console.log 行并返回 false,然后从 api 调用中获取结果

标签: angulartypescript

解决方案


您可以将订阅 userService 放在构造函数中,然后在成功返回时将您的值传递给“已登录”函数:

constructor() {
    this.userService.getUser(this.user.userName).subscribe(result => {
        // Could put if statement here to test whether result undefined / valid
        isLoggedIn(result);
    });
};

isLoggedIn(userStatus) {
    // Test and take action with userStatus value
}

推荐阅读