Reputation: 187
I've newly been trying out the Ionic framework. I'm currently trying to make a movie reviews app, using this movie reviews API.
I'm able to retrieve the JSON successfully, but not able to extract the data.
Controller code:
constructor(public navCtrl: NavController, public http: Http) {
this.http.get('https://api.nytimes.com/svc/movies/v2/reviews/all.json?api-key=a96736504fda41f58b3af1ec5876d3b9')
.map(res => res.json())
.subscribe(data => {
this.posts = data.results;
});
}
HTML code:
<ion-content>
<ion-list>
<ion-item ng-repeat = "post in posts">
{{post.display_title}}
</ion-item>
</ion-list>
</ion-content>
I get the error
Cannot read property 'display_title' of undefined.
But there is a field for display_title
. Where am I going wrong?
Upvotes: 1
Views: 1107
Reputation: 8468
That is because your data is retrieved asynchronously. When your DOM is loaded, the data has not reached back yet, hence your posts
is empty, and you will get undefined.
Also, use *ngFor
:
To solve the problem, use Elvis operator.
<ion-content>
<ion-list>
<ion-item *ngFor= "let post of posts">
{{post?.display_title}}
</ion-item>
</ion-list>
</ion-content>
Or use an async
pipe:
<ion-content>
<ion-list>
<ion-item *ngFor= "let post of posts | async">
{{post.display_title}}
</ion-item>
</ion-list>
</ion-content>
Upvotes: 1
Reputation: 44659
Just like @CozyAzure says, in this line:
{{ post.display_title }}
the view is trying to access the display_title
of something that has not being set yet (since it's being set when the asynchronous method is ready). That's why you get the following error:
Cannot read property 'display_title' of undefined.
So first, use the elvis operator to let angular know that it should not try to read the display_title
property if the post
is null:
<ion-content>
<ion-list>
<ion-item *ngFor= "let post of posts">
{{post?.display_title}}
</ion-item>
</ion-list>
</ion-content>
Please notice that the proper sintax of the ngFor loop is
*ngFor= "let post of posts">
and not
*ngFor= "let post for posts">
And also notice that you tried to use AngularJs in your view (ng-repeat = "post in posts"
) but Ionic 2/3 (or just Ionic) is built on top of Angular, so refer to these docs to find some more info about how to do things like a for loop.
Upvotes: 0