-1

I have an Angular function that I'm trying to test if the user is valid by comparing their credentials against the database:

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

Robbie Mills
  • 2,705
  • 7
  • 52
  • 87
  • 1
    Possible duplicate of [Angular method returns as undefined rather than JSON object](https://stackoverflow.com/questions/38221961/angular-method-returns-as-undefined-rather-than-json-object) – Reactgular Apr 14 '19 at 13:51
  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Heretic Monkey Apr 14 '19 at 13:51

1 Answers1

1

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:

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
}
Matt Saunders
  • 3,538
  • 2
  • 22
  • 30