我正试图解析来自Ionic api的一些JSON数据,以便在网上找到一些教程,但是最近在Ionic 2中发生了一些变化,因为它们都不起作用。
以下是我所拥有的:
import {Component} from '@angular/core';
import {NavController} from 'ionic-angular';
import {Http} from '@angular/http';
@Component({
templateUrl: 'build/pages/home/home.html'
})
export class HomePage {
items : any;
//http://api.randomuser.me/?results=10
constructor(private navController: NavController, private http: Http) {
this.http.get("http://api.randomuser.me/?results=10").subscribe(data => {
console.log("Got data");
this.items=JSON.parse(data._body).results; // this is the error
console.log(this.items);
});
}
itemClicked(event, item) {
console.log(item.title);
//console.log(event);
}
}在终端中,我可以看到错误:data._body - Property '_body‘是私有的,只能在类'Response'.中访问。
我能做什么?
发布于 2016-07-08 01:02:26
data._body for data.text(),
而不是data.text(),然后解析它,应该使用data.json()
this.items = data.json();https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data
发布于 2016-09-13 17:09:51
它在新版本中已经改变了,尝试如下
this.items= JSON.parse(data['_body']).results;
发布于 2017-05-24 08:46:16
因为Ionic 2改变了一点,我想我应该和大家分享我的做法。
要访问map函数,我们需要在import语句下添加这一行
import 'rxjs/add/operator/map';然后将构造函数更改为..。
this.http.get("http://api.randomuser.me/?results=10").map(res => res.json()).subscribe(data => {
console.log("Got data");
console.log(this.data);
});
}现在,我们可以在控制台中看到一个JSON字符串。
注意,我们添加的唯一额外位是.map(res => res.json() )。
有一个叫约书亚·莫罗尼的家伙,他做了很多Ionic 2视频,如果你很难从API:https://www.youtube.com/watch?v=vuc4dp0qHSc&index=33&list=PLvLBrJpVwC7ocO1r-xu218C15iE9gTWBA获得数据的话,你应该检查一下。
https://stackoverflow.com/questions/38255717
复制相似问题