Angular 无法从离子2中的Http访问数据
我试图在Ionic 2中使用HTTP从Blogspot API获取数据。 我所有的代码都在下面 这是我创建的与HTTP和组件接口的服务Angular 无法从离子2中的Http访问数据,angular,http,ionic2,Angular,Http,Ionic2,我试图在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) => {
**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>
每个对象项中都有标题和内容等元素。但是,我一个也找不到
我试过了,但没用
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最初得到的数据是未定义的 在网格中使用*ngIf以确保在收到数据后加载循环。 正如@echonax建议的那样,它应该循环遍历项目 第二条路
<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>
我想应该是第一种方法对我不起作用,但第二种方法对我起作用。非常感谢你!
<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>