Angular - ERROR TypeError: Cannot read properties of undefined (reading 'message') at AuthComponent.tokenHandler

Angular - ERROR TypeError: Cannot read properties of undefined (reading 'message') at AuthComponent.tokenHandler

我有 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": "Successfully Logged In"

因为它在 POSTMAN 上

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') at AuthComponent.tokenHandler (auth.component.ts:59)

这是它指向的线:

this.toastr.success(data.message);

如何解决这个问题?

谢谢

这样做

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

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

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

var cors = require('cors')

app.use(cors());

我把登录方式改成了

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