制作一个Angular函数等待订阅完成

时间:2019-04-14 13:37:31

标签: angular typescript

我有一个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调用中获取结果

1 个答案:

答案 0 :(得分:1)

您可以将对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
}