Boursomaster
Boursomaster

Reputation: 230

how to await an http response with angular?

Got a component (login) which call threw a service my controller. The controller return a false if the login fail or the email of the user if it works. My front call the service when i click on a button which execute the function OnSubmit(). In this method i would like to redirect the user on a page if the login succes, or wirte a message is there is a problem.

My problem is that my service manage to login, but since the http request of the service is async, my front doesn't wait the response and the value of this.Email is "undefined".

what should i do for wait the http response (in my component or in my service) ?

Here is my function OnSubmit() :

  onSubmit() {
    var user = {
      'Email': this.userForm.Email,
      'Password': this.userForm.Password,
    }
    this.authService.login(user).subscribe(result => {
      this.Email = result.value;
      console.log("connected with :" + this.Email);
    });

    if (this.Email == false) {
      this.Message = "wrong login or password."
    }
    else {
      this.router.navigateByUrl("dashboard");
    }   
  }

My service :

  login(user: any): Observable<any> {
    return this.http.post<any>(this.baseUrl + '/login', user, httpOptions);
  }

And my controller :

[HttpPost("/login")]
public async Task<IActionResult> Login([FromBody] LoginVM loginVM)
{
    if (ModelState.IsValid)
    {
        var result = await _signInManager.PasswordSignInAsync(
            loginVM.Email,
            loginVM.Password,
            loginVM.RememberMe,
            false
        );
        if (result.Succeeded)
        {
            return Ok(Json(loginVM.Email));
        }
        else
        {
            return Ok(Json(false));
        }
    }
    return Ok(Json(false));
}

Thanks a lot for your answers :)

Upvotes: 2

Views: 3820

Answers (2)

Rafael Nicolas Trozzo
Rafael Nicolas Trozzo

Reputation: 21

You can also convert the observable to a Promise on the onSubmit() method (making it async) and use await:

let result = await this.authService.login(user).toPromise();
this.Email = result.value;
console.log("connected with :" + this.Email);
if (this.Email == false) {
  this.Message = "wrong login or password."
}
else {
  this.router.navigateByUrl("dashboard");
}   

Upvotes: 0

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Instead of trying to force it to be synchronous, move the check of the result inside the "success" handler in the subscription, right after you assign the result to this.Email

Upvotes: 1

Related Questions