How to read [object object] using angular-2


#1

I was trying to read the json file in my application, but it only shows me: “[object object]”

This is the json file:


[
  {
    "product": "URL shortener",
    "version": "m1",
    "error": "false",
    "time": "false",
    "domin": "https://goo.gl/",
    "code": "SLnH/",
    "shortUrl": "https://goo.gl/SLnH",
    "longUrl": "test"
  }
]

in home.html:

  <ion-list  >
    <ion-item text-wrap *ngFor="let item of jsonData">
      <p>{{item}} </p> 
    </ion-item>
  </ion-list>

But unfortunately this result:

All I want is: to show the information in the json file

##updata:
home.ts:

import { Component } from '@angular/core';

import { NavController, LoadingController } from 'ionic-angular';
import {HttpProvider} from '../../providers/http-provider';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers:[HttpProvider]
})
export class HomePage {

  jsonData: any;
  loading: any;

  constructor(public navCtrl: NavController, private httpProvider:HttpProvider,public loadingCtrl: LoadingController) {

    this.loading = this.loadingCtrl.create({
      content: `
      <ion-spinner ></ion-spinner>`
    });

    this.getdata();
  }

  getdata(){
    this.loading.present();
    this.httpProvider.getJsonData().subscribe(
      result => {
        this.jsonData=result; 
        console.log("Success : "+this.jsonData); 
      },
      err =>{
        console.error("Error : "+err);
      } ,
      () => {
        this.loading.dismiss();
        console.log('getData completed');
      }
    );
  }

}


Ionic List from Object
#2

@el0zahaby It’s calling the toString() method of the object and printing [object object]. Try to use the Angular2 json pipe to display the contents:

<p>{{ item | json }}</p>


#3

But the json file will be plain text, and I will not be able to read it in a list!

I mean I want to read it as follows:

  <ion-list  >
    <ion-item text-wrap *ngFor="let item of jsonData"  >
      <p  >{{ item.product }} </p> 
      <p  >{{ item.version }} </p> 
      <p  >{{ item.error }} </p> 
      <p  >{{ etc.. }} </p> 
    </ion-item>

But I do not know how !


#4

@el0zahaby You must convert from json string to a javascript object first:

@Component(...)
export class MyPage {

	public jsonObject: any;

	private retrieveJson() {
		let jsonData: string = this.myService.getJsonString();
		this.jsonObject = JSON.parse(jsonData);
	}
}

and then:

<ion-item text-wrap *ngFor="let item of jsonObject" >

A better approach is convert to an object in the service itself. If you are doing an http request you can do something like:

my.service.ts:

public myServiceMethod(): Observable<MyObject> {
	return this.http.get('[url]').map(
		res => res.json() // Transform the JSON string in an object
	);
}

my.component.ts:

private retrieveJson() {
	this.myService.myServiceMethod().subscribe(
		jsonObject => this.jsonObject = jsonObject
	);
}

Update

Now that I’ve seen you updated code, I don’t know what your method httpProvider.getJsonData() does, but I think that you should do what I explained above about the http call (converting the string to an object)


#5

Please post your HttpProvider.

You have one very serious problem with your code, and a couple of things that you really should fix as well.

  • Don’t use any. Define interfaces and use them.
  • Get rid of the providers on your components. They cause needless instantiation of multiple providers.

Now for the big one: never store loading indicators in object properties. Always make them lexically scoped. This guards against bugs like the one you have here. Call getdata() twice, and your app will crash.


#6

HttpProvider is :http-provider.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the HttpProvider provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/

@Injectable()
export class HttpProvider {

  constructor(public http: Http) {
    console.log('Hello HttpProvider Provider');
  }

  getJsonData(){
    return this.http.get('http://URL_TO_JSON_FILE').map(res => res.json());
  }

}
 

#7

Then your proposed <p>{{item.product}}</p> should work.


#8

The solution has been solved :slight_smile: Thanks a lot
html code:


<ion-content padding>
  <ion-list *ngFor="let item of jsonData"  >
    <ion-item text-wrap  >
      <p>{{ item.product}}</p> 
    </ion-item>
    <ion-item text-wrap  >
      <p>{{ item.error}}</p> 
    </ion-item>
    <ion-item text-wrap  >
      <p>{{ item.etc}}</p> 
    </ion-item>
  </ion-list>
</ion-content>