【问题标题】:Angular, get status code value from post requestAngular,从发布请求中获取状态码值
【发布时间】:2019-04-18 14:27:30
【问题描述】:

我想从发布请求中获取 StatusCode 值,以便在我的组件中使用它。 这就是我所做的:
API调用:

  Login(user: User) {
    return this.http.post(apiUrl + 'account/Login', user).subscribe();
  }

组件中的方法:

  Login() {
    this.user.UserName = this.loginForm.controls.userName.value;
    this.user.Password = this.loginForm.controls.password.value;

    this.api.Login(this.user)
  }

现在它只显示为错误 结果应该是这样的:

更新
这不是 cors 问题...
登录成功:

【问题讨论】:

  • 你的后端服务器是什么?
  • @KhaledSameer asp.net 核心

标签: angular angular7 http-status-code-401


【解决方案1】:

在您的订阅中添加一个错误回调以捕获来自 HTTP Observable 的错误。

Login(user: User) {
    return this.http.post(apiUrl + 'account/Login', user).subscribe(
        (data) => {

        },
        (error) => {
           console.log(error);
           // get the status as error.status
        })
}

如果您想获得所有状态码,无论成功或失败,您都必须在请求中观察response

让你的 API 调用如下:

this.http.post(apiUrl + 'account/Login', user, {observe: 'response'})

记录响应以查看如何访问状态。

【讨论】:

  • 这可行,但如何显示成功登录状态代码?例如:成功登录服务器返回状态码 200。
  • @Storm 如果您想要无论成功或失败的状态,请查看更新的代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-17
  • 1970-01-01
  • 2021-05-18
  • 1970-01-01
  • 2017-09-06
  • 1970-01-01
相关资源
最近更新 更多