【问题标题】:Angular - ERROR TypeError: Cannot read properties of undefined (reading 'message') at AuthComponent.tokenHandlerAngular - 错误类型错误:无法在 AuthComponent.tokenHandler 处读取未定义的属性(读取“消息”)
【发布时间】:2022-02-22 19:26:24
【问题描述】:

我有 ASP.NET Core Web API 作为后端,Angular-13 作为前端。

成功后,POSTMAN 上的端点给出:

{
   "status_code": 200,
   "message": "Successfully Logged In",
   "result": {
       "token": "gggggffffffffffffdddddddddddd",
       "user": {
           "id": 3,
           "user_name": "smith",
           "last_login": "2022-01-03T12:35:26.0305649"
          },
       "roles": [
           "Teacher"
       ],
       "expires": "2022-01-03T14:40:33Z"
   }
}

那么对于错误,我有:

{
    "statusCode": 500,
    "message": "Value cannot be null. (Parameter 'user')"
}

当在 Angular 前端登录成功时,我想显示消息:

message": "登录成功"

因为它在邮递员上

auth.component:

login(){
  this.authService.login(this.loginForm.value).subscribe({
    next: (res) => this.toastr.success(res.message),
    error: (error) => {
      this.toastr.error(error.message);
    }
  })
}

我收到了这个错误:

ERROR TypeError: Cannot read properties of undefined (reading 'message') 在 AuthComponent.tokenHandler (auth.component.ts:59)

这是它指向的线:

this.toastr.success(data.message);

我该如何解决这个问题?

谢谢

【问题讨论】:

  • 为什么你需要在auth.component.ts明确next:error:
  • @Chaka15 - 你是什么意思?
  • 为什么在subscribe 中同时使用{}next:error:?你能把它去掉,写两个普通的箭头函数吗?
  • 做这个 tokenHandler(message: any){ this.toastr.success(message); } 因为你已经传递了消息。
  • @Chaka15 这一点都不奇怪。从 rxjs6.4 开始,所有接受超过 1 个参数的订阅签名都已弃用。你可以阅读它here

标签: angular asp.net-web-api


【解决方案1】:

这样做

tokenHandler(message: any){
  this.toastr.success(message);
}

因为您已经在函数中传递了消息。

【讨论】:

    【解决方案2】:

    如果在 nodejs 项目中没有分配这个然后生成这个

    var cors = require('cors')

    app.use(cors());

    【讨论】:

      【解决方案3】:

      我把登录方式改成了

      login() {
      this.authService.login(this.loginForm.value).subscribe(res => {
        this.toastr.success(res.message)
      }, (error) => {
        this.toastr.error(error.message);
      });}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-05
        • 2021-12-16
        • 1970-01-01
        • 2018-04-29
        • 1970-01-01
        • 2021-12-03
        • 2021-11-22
        • 2019-04-15
        相关资源
        最近更新 更多