简体   繁体   English

如何等待带有角度的http响应?

[英]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.如果登录失败,则控制器返回 false,如果成功,则返回用户的电子邮件。 My front call the service when i click on a button which execute the function OnSubmit().当我单击执行函数 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".我的问题是我的服务设法登录,但由于服务的 http 请求是异步的,所以我的前端不等待响应并且 this.Email 的值为“未定义”。

what should i do for wait the http response (in my component or in my service)?我应该怎么做才能等待 http 响应(在我的组件或我的服务中)?

Here is my function OnSubmit():这是我的函数 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:)非常感谢你的回答:)

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不要试图强制它同步,而是在将结果分配给this.Email之后立即将结果检查移动到订阅中的“成功”处理程序中

You can also convert the observable to a Promise on the onSubmit() method (making it async) and use await:您还可以将 observable 转换为 onSubmit() 方法上的 Promise (使其异步)并使用 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");
}   

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

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