brians69
brians69

Reputation: 485

Angular 2 not displaying data from HTTP

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.

Upvotes: 0

Views: 400

Answers (1)

Peter Pompeii
Peter Pompeii

Reputation: 1445

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.

Upvotes: 1

Related Questions