Parse JSON with Ionic 2 and typescript

22,886

Solution 1

data._body for data.text(),

Instead of data.text() then parsing it you should use data.json()

this.items = data.json();

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

Solution 2

It has changed in the new versions try this

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

Solution 3

Because Ionic 2 has changed a wee bit I thought I'd share the way I do it.

To access a map function we need to add this line under your import statements

import 'rxjs/add/operator/map';

then change your constructor to...

        this.http.get("http://api.randomuser.me/?results=10").map(res => res.json()).subscribe(data => {
        console.log("Got data");
        console.log(this.data);
    });
}

Now we can see a JSON string in the console.
Note the only extra bit we added is .map(res => res.json()

There is a guy Joshua Morony who does a lot of Ionic 2 videos that you should check out if you are struggling with getting data from an API: https://www.youtube.com/watch?v=vuc4dp0qHSc&index=33&list=PLvLBrJpVwC7ocO1r-xu218C15iE9gTWBA

Share:
22,886
André Oliveira
Author by

André Oliveira

I enjoy making scalable web apps using Serverless, Node.js and AWS.

Updated on May 24, 2020

Comments

  • André Oliveira
    André Oliveira almost 4 years

    I'm trying to parse some JSON data from randomuser.me api, to do that a found some tutorials online but aparrently something have change recently in Ionic 2, because none of them are working.

    Here is what i have:

    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);
      }
    
    
    }
    

    In the terminal i can see the error: data._body - Property '_body' is private and only accessible within class 'Response'.

    What can i do?

  • Yokesh Varadhan
    Yokesh Varadhan almost 7 years
    how could i show the values to html like {{data.something}}
  • Jack Nutkins
    Jack Nutkins over 6 years
    This here is the answer as of 15/09/2017. Thanks a lot @rawturtle.