0

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!

1
  • You can use *ngIf statement or check if candidate is exists like this {{candidate?.phone}} Commented Sep 9, 2020 at 10:24

1 Answer 1

2

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}}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.