0

I'm doing an HTTP request using Angular 2, but the results aren't being displayed. I have the following service:

getData() {
  return this.http.get(this.api)
    .toPromise()
    .then(response => response.json())
    .catch(this.handleError);
}

Here's my AppComponent:

info: any;
error: any;

constructor(private appService: AppService) {}

getData() {
  this.appService
    .getData()
    .then(response => this.info = response)
    .catch(error => this.error = error);
}

ngOnInit() {
  this.getData();
}

On my template, I'm calling {{info.fields.id}} but it gives me an error: ORIGINAL EXCEPTION: TypeError: Cannot read property 'data' of undefined.

Any hints on what I'm doing wrong?

I also created a Plunker to reproduce this issue.

4
  • 1
    Because you are trying to retrieve data when it's not ready (not yet returned from http call). Use safe operator instead in your view: fruit: {{info?.data?.fruit}} Commented Aug 8, 2016 at 1:01
  • I see, thanks for the tip. Is it a good practice, though? It feels weird to me. :P Commented Aug 8, 2016 at 1:07
  • 1
    All things were invented for some reasons, weren't they? Another approach is to wrap it with <div *ngIf="info"> to make sure the info is available before your code is called. The gist is to ensure the readiness of data before processing it. Commented Aug 8, 2016 at 1:10
  • Yeah, it makes sense. Thanks, again. =) Commented Aug 8, 2016 at 1:12

1 Answer 1

1

Try using the safe navigation (Elvis) operator in your template, for example fruit: {{info?.data?.fruit}}. You can find more information about the safe operator here

This is needed because your service is returning a promise. In the getData() method of your controller, you are using that promise and with .then() you're setting the info property on the controller. The problem is that the view is rendering before your promise is completely resolved.

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.