Reputation: 250
I have an .html
file where I use {{candidate.phone}}
and I can see the result on page but in console have error ERROR TypeError: Cannot read property 'phone' of undefined
.
If I correctly understand it's 'cause ngOnInit
doesn't waiting for the response of getCandidate()
, so the question is how can I call this function after it's completely finished?
Here's my code:
candidate: ICandidatesInfo;
ngOnInit(): void {
this.getCandidate();
}
getCandidate() {
this.candidateInfoService
.getById(this.route.snapshot.params['id'])
.subscribe(candidate => this.candidate = candidate);
}
In service:
getById(id: string): Observable<ICandidatesInfo> {
return this.http.get<ICandidatesInfo>(`${this.url}/${id}`);
}
Would be really grateful for any help!
Upvotes: 0
Views: 106
Reputation: 14792
You have 3 options :
1- use *ngIf
<span *ngIf="candidate && candidate.phone">{{candidate.phone}}</span>
2- set default value for your model (candidate)
candidate: ICandidatesInfo={phone:null , ... }
3- use ?
{{candidate?.phone}}
Upvotes: 2