Angular,从post请求获取状态代码值

问题描述 投票:0回答:1

我想从post请求中获取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)
  }

现在它只显示为错误enter image description here结果应该是:enter image description here

更新 这不是cors问题...... 成功登录:enter image description here

angular angular7 http-status-code-401
1个回答
0
投票

在订阅中添加错误回调以捕获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'})

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

© www.soinside.com 2019 - 2024. All rights reserved.