我收到以下错误:无法在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>
您创建用户对象,但未定义。因此,您有两种解决方案。
第一种方法是在构造函数中初始化用户
constructor(){
this.user={id:null,name:null};
}
第二种方法是在html中进行自我分配 {{user?.id}}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句