【问题标题】:Parse JSON with Ionic 2 and typescript使用 Ionic 2 和 typescript 解析 JSON
【发布时间】:2016-11-10 09:02:45
【问题描述】:

我正在尝试从 randomuser.me 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 - 属性“_body”是私有的,只能在“Response”类中访问。

我能做什么?

【问题讨论】:

    标签: typescript angular ionic2


    【解决方案1】:

    data._body 用于 data.text(),

    而不是data.text() 然后解析它你应该使用data.json()

    this.items = data.json();
    

    https://angular.io/docs/ts/latest/guide/server-communication.html#!#extract-data

    【讨论】:

      【解决方案2】:

      新版本有变化试试这个

      this.items= JSON.parse(data['_body']).results;

      【讨论】:

        【解决方案3】:

        因为 Ionic 2 发生了一些变化,所以我想我会分享一下我的做法。

        要访问地图功能,我们需要在您的导入语句下添加这一行

        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()

        有一个人 Joshua Morony 制作了很多 Ionic 2 视频,如果您正在努力从 API 获取数据,您应该查看这些视频:https://www.youtube.com/watch?v=vuc4dp0qHSc&index=33&list=PLvLBrJpVwC7ocO1r-xu218C15iE9gTWBA

        【讨论】:

        • 我怎样才能将值显示为 html 像 {{data.something}}
        • 这是截至 2017 年 9 月 15 日的答案。非常感谢@rawturtle。
        猜你喜欢
        • 2017-08-21
        • 2018-01-01
        • 1970-01-01
        • 2016-02-23
        • 1970-01-01
        • 1970-01-01
        • 2011-05-08
        • 2016-07-31
        • 1970-01-01
        相关资源
        最近更新 更多