TypeError:未定义(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}}

最新更新