我正在尝试使用Ionic 2中的HTTP从Blogspot API获取数据。我的所有代码都在
下面这是我与HTTP和组件交互的服务。
**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;
}
);
}
}
这是我为测试数据创建的组件。
**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)
);
}
这是组件模板
**Component template**
<ion-content padding>
<button ion-button (click) = "serverDataCall()" > get </button>
</ion-content>
当我单击按钮时,它在控制台中显示一个对象,
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"
在每个对象项目中都有诸如标题和内容之类的元素。但是,我无法检索任何一个。
我尝试过,但它没有用!
serverDataCall(){
this.httpData.getData().subscribe(
(datas : any []) => this.data = datas, //changed this line
(error) => console.log(error)
);
}
,在模板中,
<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>
什么都没有!它给了我错误,例如未定义!
您的视图是在收到数据之前加载的,并且您的*ngFor
最初将datas
作为CC_2。
在网格中使用*ngIf
,以确保收到数据后的循环加载。@echonax建议它应该通过items
循环。
<ion-content padding>
<button ion-button (click) = "serverDataCall()" > get
lyrics</button>
<ion-grid *ngIf="datas && datas.items">
<ion-row *ngFor="let data of datas.items">
<ion-col>
{{data.title}}
</ion-col>
</ion-row>
<ion-grid>
</ion-content>
serverDataCall(){
this.httpData.getData().subscribe(
(datas : any []) => this.data.items = datas, //you can either do this and keep the the template code the same
(error) => console.log(error)
);
}
第二条方法
<ion-content padding>
<button ion-button (click) = "serverDataCall()" > get
lyrics</button>
<ion-grid>
<ion-row *ngFor="let data of datas.items"> // or change it in the template and leave the service method unchanged
<ion-col>
{{data.title}}
</ion-col>
</ion-row>
<ion-grid>
</ion-content>