I'm trying to get the data from Blogspot API using HTTP in Ionic 2. All of my codes are below
This is the service that I created to interface with HTTP and components.
**HttpService.ts**
export class Serverdata {
constructor(private http: Http) { }
getData() {
return this.http.get(this.blogUrl)
.map(
(response: Response) => {
const datas = response.json();
return datas;
}
);
}
}
This is the component that I created to test the data.
**Component.ts**
constructor(public navCtrl: NavController, public navParams:
NavParams, private httpData : Serverdata) {}
serverDataCall(){
this.httpData.getData().subscribe(
(datas) => console.log(datas),
(error) => console.log(error)
);
}
And here is the component template
**Component template**
<ion-content padding>
<button ion-button (click) = "serverDataCall()" > get </button>
</ion-content>
When I click the button, it shows an object in the console which is something like this,
Object {kind: "blogger#postList",
nextPageToken:"CgkIChihsOeVtioQo9Cj3-vl17BF",
items: Array(10),
etag:
""h3phi6z0oROkI1XWpXsALUFHLuA/MjAxNy0wMy0zMVQwMjoxMzowNy45Mjda""}
etag:
""h3phi6z0oROkI1XWpXsALUFHLuA/MjAxNy0wMy0zMVQwMjoxMzowNy45Mjda""
items:Array(10)
0:Object
1:Object
2:Object
3:Object
4:Object
5:Object
6:Object
7:Object
8:Object
9:Object
length:10
kind:"blogger#postList"
There are elements such as title and content with in each of the object items. But, I wasn't able to retrieve any of them.
I tried this, but it didn't work!
serverDataCall(){
this.httpData.getData().subscribe(
(datas : any []) => this.data = datas, //changed this line
(error) => console.log(error)
);
}
And in template,
<ion-content padding>
<button ion-button (click) = "serverDataCall()" > get
lyrics</button>
<ion-grid>
<ion-row *ngFor="let data of datas">
<ion-col>
{{data.title}}
</ion-col>
</ion-row>
<ion-grid>
</ion-content>
Nothing worked! It gives me errors such as undefined!
2nd way
You are getting undefined because your view is loaded before the data is received and your
*ngFor
is gettingdatas
asundefined
initially.use an
*ngIf
in the grid to make sure the loop loads after data is received. Also as @echonax suggests it should loop throughitems
.