error : Cannot set property 'id' of undefined at UserComponent

error : Cannot set property 'id' of undefined at UserComponent

我收到以下错误:无法在 UserComponent.push../src/app/users/user/user.component.ts.UserComponent

处设置未定义的 属性 'id'

TS代码

import { Component, OnInit } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";

@Component({
  selector: "app-user",
  templateUrl: "./user.component.html",
  styleUrls: ["./user.component.css"],
})
export class UserComponent implements OnInit {
  user: { id: number; name: string };

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.user.id = +this.route.snapshot.params['id'];
  }
}

模板:

<p>User with ID {{user.id}} loaded.</p>
<p>User name is {{user.name}}</p>

因为您还没有初始化您的 user 组件 属性 这就是错误的原因。因此,在您的场景中,user 值未定义。

您可以使用模板中的 safe navigation operation 来解决这个问题。即使您的值为 undefinednull.

,它也会呈现您的 UI 而不会出现任何错误
<p>User with ID {{user?.id}} loaded.</p>
<p>User name is {{user?.name}}</p>

另一种方法是使用默认值初始化值。

export class UserComponent implements OnInit {
 // Assign the values with default values of corresponding(string in this case) types.
  user: { id: number, name: string } = {id: '', name: ''};

  constructor(private route: ActivatedRoute) {}

  ngOnInit() {
    this.user.id = +this.route.snapshot.params['id'];
  }
}

您创建了用户对象但未定义。所以你有两个解决方案。

第一种方式是在构造函数中初始化用户

constructor(){
   this.user={id:null,name:null};  
}

第二种方式是在html中进行自我赋值{{user?.id}}