简体   繁体   English

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

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

I have an Angular function that I'm trying to test if the user is valid by comparing their credentials against the database: 我有一个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')      
}

How can I make the function wait for my subscribe to finish? 如何使函数等待我的订阅完成? Right now it's going straight through to the console.log line and returning false, and then getting the results back from the api call 现在,它直接进入console.log行并返回false,然后从api调用中获取结果

You could put your subscription to userService in your constructor function, and then pass your value to an 'is logged in' function on successful return: 您可以将对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