Reputation: 441
I'm fetching API data using AngularJS/Ionic 2. I've followed this guide and get it to properly log the data when I go to home.html. But when I try to actually display the data in home.html I can't get it to work.
data-provider.ts:
getRemoteData(){
this.http.get('https://api.example.com/?limit=10').map(res => res.json()).subscribe(data => {
console.log(data);
});
}
home.ts:
ionViewDidLoad(){
this.dataService.getRemoteData();
}
This correctly logs JSON data:
[
{
"id": "a",
"name": "ExampleA",
"price": "10"
},
{
"id": "b",
"name": "ExampleB",
"price": "15"
}
]
I've tried returning the data instead of logging the data, then creating a variable data: any;
in the home.ts and outputting the data in home.html as <p> data[0].name </p>
but I kept getting the error message, Can't read property '0' of undefined
Upvotes: 1
Views: 469
Reputation: 8065
Two point: you have either to assign the value from the request to a component's property and in the template wait for this property to be assigned.
Your service/provider should be (only):
getRemoteData(){
return this.http.get('https://api.example.com/?limit=10')
.map(res => res.json());
}
you shouldn't subscribe to the observable in it. Do this in the component:
ionViewDidLoad(){
this.dataService.getRemoteData().subcribe( response => this.data = response);
}
in the template, as mentioned before, check if the 'data' exists:
<p *ngIf="data">data[0].name </p>
Upvotes: 3