繁体   English   中英

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

[英]Make an Angular function wait for the subscribe to finish

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM