TypeError: property of undefined (Angular)

TypeError: property of undefined (Angular)

我有一个 .html 文件,我在其中使用 {{candidate.phone}},我可以在页面上看到结果,但在控制台中有错误 ERROR TypeError: Cannot read property 'phone' of undefined。 如果我理解正确是因为 ngOnInit 没有等待 getCandidate() 的响应,那么问题是我如何在它完全完成后调用这个函数?

这是我的代码:

candidate: ICandidatesInfo;
    
ngOnInit(): void {
  this.getCandidate();
}

getCandidate() {
  this.candidateInfoService
    .getById(this.route.snapshot.params['id'])
    .subscribe(candidate => this.candidate = candidate);
}

在役:

getById(id: string): Observable<ICandidatesInfo> {
  return this.http.get<ICandidatesInfo>(`${this.url}/${id}`);
}

非常感谢任何帮助!

您有 3 个选项:

1- 使用*ngIf

<span *ngIf="candidate && candidate.phone">{{candidate.phone}}</span>

2- 为您的模型设置默认值(候选人

candidate: ICandidatesInfo={phone:null , ... }

3- 使用?

{{candidate?.phone}}