当我想在evenement组件中显示Medecin数据的用户类的标签“ Nom”时,我收到此错误消息:
RROR TypeError: Cannot read property 'Users' of undefined
at Object.eval [as updateRenderer] (EvenementComponent.html:34)
at Object.debugUpdateRenderer [as updateRenderer] (core.js:36078)
at checkAndUpdateView (core.js:35061)
at callViewAction (core.js:35421)
at execEmbeddedViewsAction (core.js:35378)
at checkAndUpdateView (core.js:35056)
at callViewAction (core.js:35421)
at execEmbeddedViewsAction (core.js:35378)
at checkAndUpdateView (core.js:35056)
at callViewAction (core.js:35421)
这是我的代码:
evenement.component.html:
<ng-template pTemplate="header">
<tr>
<th>Medecin</th>
</tr>
</ng-template>
<ng-template pTemplate="body" let-rowData let-evenement >
<tr [pSelectableRow]="rowData">
<td>{{evenement.Medecin.Users.Nom}}</td>
</tr>
</ng-template>
evenement.component.ts:
evenement: Evenement = new Evenement();
evenements: Evenement[] = [new Evenement()];
Users: User[];
Medecins: Medecin[];
constructor(private router: Router, private evenementService: EvenementService, private http: HttpClient, private messageService: MessageService) {
this.evenementService.GetMedecins().subscribe(medecins => this.Medecins = medecins);
}
ngOnInit() {
// console.log(this.evenements);
this.evenementService.GetEvenements().subscribe(evenements => this.evenements = evenements);}
Evenement.ts:
export class Evenement {
constructor() {
this.Medecin = new Medecin();
this.Users = new User();
}
Id: number;
Prix: number;
Medcin_Id: number;
Medecin: Medecin;
Users: User;}
Medecin.ts:
export class Medecin {
constructor() {
this.Users = new User();
}
Id: number;
Users_Id: number;
Users: User;}
User.ts:
export class User {
Id: number;
Nom: string;
Prenom: string; }
那么,有实施上的问题吗?我做错了吗?
答案 0 :(得分:0)
您可以使用安全的导航操作符?.
<td>{{evenement?.Medecin?.Users?.Nom}}</td>
答案 1 :(得分:0)
由于某些原因,该错误告诉我“用户”集合未定义(没有值),请尝试将初始化代码移到ngOnInit for Environment类中,看看是否可行。
如果这不起作用,则将断点或控制台日志登录到Mementin.ts,Evenement.ts和evenement.component.ts的ngOnInit的构造函数中。您将知道为什么它具有未定义的值。
evenement: Evenement;
evenements: Evenement[];
Users: User[];
Medecins: Medecin[];
constructor(private router: Router, private evenementService: EvenementService, private http: HttpClient, private messageService: MessageService) {
this.evenementService.GetMedecins().subscribe(medecins => this.Medecins = medecins);
}
ngOnInit() {
// console.log(this.evenements);
Evenement = new Evenement();
Evenement[] = [new Evenement()];
this.evenementService.GetEvenements().subscribe(evenements => this.evenements = evenements);
}