How to print json data in html ionic3


#1

when u go to add-bike.ts how do i print that console data in add-html

bike.html

Bike X
Name: {{bike.name}}

Vehicle Name: {{bike.bname}}

Vehicle.No: {{bike.no}}

Service Insurance +
bike.ts

import { Component } from ‘@angular/core’;
import { IonicPage, NavController, NavParams, AlertController} from ‘ionic-angular’;
import { InsPage } from ‘…/ins/ins’;
import { SerPage } from ‘…/ser/ser’;
import { AddBikePage } from ‘…/add-bike/add-bike’;
import { AddSerPage } from ‘…/add-ser/add-ser’;
import { Data } from ‘…/…/providers/data/data’;
import { Storage } from ‘@ionic/storage’

/**

Generated class for the BikePage page.
See https://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: ‘page-bike’,
templateUrl: ‘bike.html’,
})
export class BikePage {

constructor(public storage:Storage,public alertCtrl: AlertController,public navCtrl: NavController, public navParams: NavParams, public dataService: Data) {
}

public bikes = [];

ins(){
this.navCtrl.push(InsPage);
}

ser(){
// this.navCtrl.push(SerPage);
this.navCtrl.push(AddSerPage);
}

AddBike(){
this.storage.set(‘name’, ‘Anes’);
this.storage.set(‘age’, ‘52’);
let your = { “name”: “John”, “age”: 30, “car”: " " };
this.storage.set(‘my-json’, your);
console.log(this.storage.set(‘my-json’, your));
console.log(this.storage.set(‘age’, ‘52’));
this.navCtrl.push(AddBikePage);
}

ionViewDidLoad() {
this.dataService.getData().then((todos) => {
if(todos){
this.bikes = [todos];
}
});
}
// Deleting item
remove(no) {
(this.bikes).splice(no, 1);
window.localStorage.clear();
};

presentConfirm(){
let alert = this.alertCtrl.create({
// window.localStorage.getItem();
inputs: [
{
name: ‘Name’,
placeholder: ‘Name’,
value: ‘{{ service.city | json }}’,
},
{
name: ‘Bike Name’,
placeholder: ‘Bike Name’,
value: ‘{{ bike.bname | json }}’,
},
{
name: ‘Registration Number’,
placeholder: ‘Bike Registration Number’,
value: ‘{{ bike.no | json }}’,
},
],
subTitle: ‘Edit Quick Info’,
buttons: [‘Save’]
});
alert.present();
}
}

add-bike.html

Add Bike Name Bike Name Reg No
Add Todo

add-bike.ts

import { Component } from ‘@angular/core’;
import { IonicPage, NavController, NavParams, AlertController } from ‘ionic-angular’;
import { BikePage } from ‘…/bike/bike’;
import { Data } from ‘…/…/providers/data/data’;
import { Injectable } from ‘@angular/core’;
import { FormBuilder, FormGroup, Validators } from ‘@angular/forms’;
import { Storage } from ‘@ionic/storage’;
/**

Generated class for the AddBikePage page.
See https://ionicframework.com/docs/components/#navigation for more info on
Ionic pages and navigation.
*/
@IonicPage()
@Component({
selector: ‘page-add-bike’,
templateUrl: ‘add-bike.html’,
})
export class AddBikePage {
bike = {}
constructor(public storage: Storage,public alertCtrl: AlertController, public navCtrl: NavController, public navParams: NavParams, public dataService: Data) {
}

async showDetails() {
let name = await this.storage.get(‘name’);
let age = await this.storage.get(‘age’);
this.storage.get(‘my-json’).then((val) => {
console.log(‘Your Name is’,val.name);
console.log(‘Your Age is’, val.age);
console.log(‘Your Car is’, val.car);
});
if (name == ‘Anes’) {
alert(“Hi good”);
}

}
ionViewDidLoad() {
console.log(‘ionViewDidLoad PeoplePage’);
}

async ionViewDidEnter() {

await this.showDetails();
}

bikeCreate() {
let alert = this.alertCtrl.create({
subTitle: ‘Successfully Submitted!’,
buttons: [‘OK’]
});
alert.present();
this.dataService.save(this.bike);
this.navCtrl.push(BikePage);
}
}


#2

Please edit your post, it is not very readable at the moment.
Use the </> button above the input field to format your code, command line output or error message (select the text first, then click the button or wrap it in ``` manually). Check the preview if it looks better. This will make sure your text is readable and if it recognizes the programming language it also automatically adds code syntax highlighting. Thanks.


#3
bike.html
<!--
  Generated template for the BikePage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <ion-title>Bike</ion-title>
  </ion-navbar>

</ion-header>


<ion-content padding>
    <ion-card *ngFor="let bike of bikes">
    <button class="closebutton" ion-button color="danger" expandable (click)="remove(no);">X</button>
    <button class="editbutton" ion-button color="grey" expandable (click)="presentConfirm()">
       <ion-icon name="create"></ion-icon>
    </button> 
      <img src="../assets/imgs/bike-img.png">
      <ion-card-content>
          <p>
             Name: {{bike.name}}
          </p>
          <p>
            Vehicle Name: {{bike.bname}}
          </p>
          <p> 
           Vehicle.No: {{bike.no}}
          </p>
      </ion-card-content>
      <button class="services" ion-button icon-start (click)="ser()">
        <ion-icon name="star"></ion-icon>
        Service
      </button>
      <button class="insurances" ion-button icon-start (click)="ins()">
        <ion-icon name="star"></ion-icon>
        Insurance
      </button>
    </ion-card>



  <ion-fab class="plusbutton">
    <button (click)="AddBike()"  ion-fab>+</button>
  </ion-fab> 

</ion-content>

bike.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController} from 'ionic-angular';
import { InsPage } from '../ins/ins';
import { SerPage } from '../ser/ser';
import { AddBikePage } from '../add-bike/add-bike';
import { AddSerPage } from '../add-ser/add-ser';
import { Data } from '../../providers/data/data';
import { Storage } from '@ionic/storage'


/**
 * Generated class for the BikePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-bike',
  templateUrl: 'bike.html',
})
export class BikePage {
 
  constructor(public storage:Storage,public alertCtrl: AlertController,public navCtrl: NavController, public navParams: NavParams, public dataService: Data) {
  }

  public bikes = [];

  ins(){
    this.navCtrl.push(InsPage);
  }

  ser(){
    // this.navCtrl.push(SerPage);
    this.navCtrl.push(AddSerPage);
  }

  AddBike(){
    this.storage.set('name', 'Anes');
    this.storage.set('age', '52');
    let your = { "name": "John", "age": 30, "car": "ferrari" };
    this.storage.set('my-json', your);
    console.log(this.storage.set('my-json', your));
    console.log(this.storage.set('age', '52'));
    this.navCtrl.push(AddBikePage);
  }

  ionViewDidLoad() {
    this.dataService.getData().then((todos) => {
      if(todos){
        this.bikes = [todos];
      }
    }); 
  }
  // Deleting item
  remove(no) {
    (this.bikes).splice(no, 1);
    window.localStorage.clear();
  };

  presentConfirm(){
    let alert = this.alertCtrl.create({
      // window.localStorage.getItem();
      inputs: [
        {
          name: 'Name',
          placeholder: 'Name',
          value: '{{ service.city | json }}',
        },
        {
          name: 'Bike Name',
          placeholder: 'Bike Name',
          value: '{{ bike.bname | json }}',
        },
        {
          name: 'Registration Number',
          placeholder: 'Bike Registration Number',
          value: '{{ bike.no | json }}',
        },
      ],
      subTitle: 'Edit Quick Info',
      buttons: ['Save']
    });
    alert.present();
  }
}

add-bike.html

<!--
  Generated template for the AddBikePage page.

  See http://ionicframework.com/docs/components/#navigation for more info on
  Ionic pages and navigation.
-->
<ion-header>

  <ion-navbar>
    <ion-title>Add Bike</ion-title> 
  </ion-navbar>

</ion-header>

<ion-content padding>  
  <form (ngSubmit)="bikeCreate()">
    <ion-item>
      <ion-label>Name</ion-label>
      <ion-input type="text" [(ngModel)]="bike.name" name="name"></ion-input>
    </ion-item> 
    <ion-item>
      <ion-label>Bike Name</ion-label>
      <ion-textarea [(ngModel)]="bike.bname"  name="bname"></ion-textarea>
    </ion-item>
    <ion-item>
      <ion-label>Reg No</ion-label>
      <ion-input type="text" [(ngModel)]="bike.no" name="no"></ion-input>
    </ion-item>
    <p>
      <button ion-button type="submit" block><ion-icon name="bookmark"></ion-icon>Add Todo</button>
    </p>
     {{name}}
  </form>
</ion-content>

add-bike.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { BikePage } from '../bike/bike';
import { Data } from '../../providers/data/data';
import { Injectable } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { Storage } from '@ionic/storage';
/**
 * Generated class for the AddBikePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-add-bike',
  templateUrl: 'add-bike.html',
})
export class AddBikePage {
  bike = {}
  name = {}
  name1 = {}
  age = {}
  constructor(public storage: Storage,public alertCtrl: AlertController, public navCtrl: NavController, public navParams: NavParams,  public dataService: Data) {
  }
  
  async showDetails() {
    this.name = await this.storage.get('name');
    let age = await this.storage.get('age');
    this.storage.get('my-json').then((val) => {
      console.log('Your Name is',val.name);
      console.log('Your Age is', val.age);
      console.log('Your Car is', val.car);
    }); 
    if (name == 'Anes') {
      alert("Hi good");
    }

  } 
  ionViewDidLoad() {
    console.log('ionViewDidLoad PeoplePage');
  }

  async ionViewDidEnter() {

    await this.showDetails();

  } 



  bikeCreate() {
    let alert = this.alertCtrl.create({
      subTitle: 'Successfully Submitted!',
      buttons: ['OK']
    });
    alert.present();
    this.dataService.save(this.bike);
    this.navCtrl.push(BikePage);
  }
}

#4

That is some readable code now. Do you also have a problem or question you want to get solved or do you just want to show off your code?


#5

@naveesh Which json you want to show in which html? If it’s about this method that shows your alert:

  presentConfirm(){
    let alert = this.alertCtrl.create({
      // window.localStorage.getItem();
      inputs: [
        {
          name: 'Name',
          placeholder: 'Name',
          value: '{{ service.city | json }}',
        },
        {
          name: 'Bike Name',
          placeholder: 'Bike Name',
          value: '{{ bike.bname | json }}',
        },
        {
          name: 'Registration Number',
          placeholder: 'Bike Registration Number',
          value: '{{ bike.no | json }}',
        },
      ],
      subTitle: 'Edit Quick Info',
      buttons: ['Save']
    });
    alert.present();
  }
}

I don’t think it will work because you are just passing string values to the alert inputs. If you want a json string you could change value: '{{ service.city | json }}' to value: JSON.stringify(service.city) and so on (you are in the typescript file here, so you can just use plain javascript functions).


#6

i already asked question at the top.So didnt type it again.sry for the incovinence.

Below is the question

when u go to add-bike.ts how do i print that console data in add-bike.html

i want to print json data seperately.
i mean name,age,car

async showDetails() {
this.name = await this.storage.get(‘name’);
let age = await this.storage.get(‘age’);
this.storage.get(‘my-json’).then((val) => {
console.log(‘Your Name is’,val.name);
console.log(‘Your Age is’, val.age);
console.log(‘Your Car is’, val.car);
});


#7

@naveesh You could change your method to:

public myJson: any; // Instead of any, it's better to use its type

async showDetails() {
	let name = await this.storage.get('name');
	this.name = name;

	let age = await this.storage.get('age');
	let myJson = await this.storage.get('my-json'); 
	console.log('myJson', myJson); // If you want to log it in the console	
	this.myJson = myJson;
	
	if (name == 'Anes') {
		alert("Hi good");
	}
}

The method is assigning your json object to the class attribute named myJson. You can then just use it in your HTML:

<div>{{ myJson | json }}</div>


#8

it is printing {“name”:“john”,“age”:“20”,“car”:“ferri”}

but i want in this format
name:john
age:20
car:ferry


#9

here i m trying to fetch the value onclicking button but that didnt happen.

insted its printing “{{ service.city | json }}”…


#10

@naveesh About printing {“name”:“john”,“age”:“20”,“car”:“ferri”}, I did this as an example and this happens because the value is printed in json format through the angular pipe json ({{ value | json }}). To print in your desired format you can just access each value individually, like:

<div *ngIf="myObject">
	Name: {{ myObject.name }}<br>
	Age: {{ myObject.age }}<br>
	Car: {{ myObject.car }}<br>
</div>

Where myObject is the property name in your class (the name may be different, though).

I advise you to read more about how to use angular in their docs.

About your 2nd case, about showing data in the alert, make sure to pass the JSON.stringify() value to it without quotes:

value: JSON.stringify(service.city)

and not:

value: 'JSON.stringify(service.city)'

otherwise you would just be passing a plain literal string.

Have in mind that in this case you would be passing a JSON string representation to your input. I gave this example because you were using the json pipe in it (in the form obj.prop | json). I think this is not what you want. If you just want the the property value you could just do something like:

{
	name: 'Name',
	placeholder: 'Name',
	value: service.city,
}

#11

Do not reinvent NavParams using Storage. Storage is only for things that need to persist across app restarts. Using NavParams here instead will drastically simplify this code and make it much more reliable, as you will have eliminated a bunch of race conditions.


#12

throwing error when i do that


#13

@naveesh Which error when you do what? If it’s NullpointerException in service.city make sure that service is defined like service && service.city.


#14
 presentConfirm(){
    let alert = this.alertCtrl.create({
      // window.localStorage.getItem();
      inputs: [
        {
          name: 'Name',
          placeholder: 'Name',
          value:  service.city,
        },
        {
          name: 'Bike Name',
          placeholder: 'Bike Name',
          value:  service.bname ,
        },
        {
          name: 'Registration Number',
          placeholder: 'Bike Registration Number',
          value:  service.no',
        },
      ],
      subTitle: 'Edit Quick Info',
      buttons: ['Save']
    });
    alert.present();
  }

#15

error: service not defined…But i defined it as public

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController} from 'ionic-angular';
import { InsPage } from '../ins/ins';
import { SerPage } from '../ser/ser';
import { AddBikePage } from '../add-bike/add-bike';
import { AddSerPage } from '../add-ser/add-ser';
import { Data } from '../../providers/data/data';
import { Storage } from '@ionic/storage'


/**
 * Generated class for the BikePage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: 'page-bike',
  templateUrl: 'bike.html',
})
export class BikePage {
 
  constructor(public storage:Storage,public alertCtrl: AlertController,public navCtrl: NavController, public navParams: NavParams, public dataService: Data) {
  }

  public bikes = [];

  public items = [];

  public item = [];

  public bike = [];

  public obj = {};

  public service = {};
  ins(){
    this.navCtrl.push(InsPage);
  }

  ser(){
    // this.navCtrl.push(SerPage);
    this.navCtrl.push(AddSerPage);
  }

  AddBike(){
    // this.storage.set('name', 'Anes');
    // this.storage.set('age', '52');
    // let your = { "name": "John", "age": 30, "car": "ferrari" };
    // var json = '{"result":true, "count":42}';
    // var obj = JSON.parse(json);
    // console.log(obj.count);
    // console.log(obj.result);
    // this.storage.set('my-json', your);
    // console.log(this.storage.set('my-json', your));
    // console.log(this.storage.set('age', '52'));
    this.navCtrl.push(AddBikePage);
  }

  ionViewDidLoad() {
    var items = this.storage.get('bike');
    // var items = JSON.parse(item,);
    console.log(items);
    // this.navCtrl.push(BikePage);

    this.items = [
      { title: 'John', description: 'name', color:'red', type:'car' },
      { title: 'adr', description: 'name', color: 'red', type: 'bike' },
      { title: 'ferrari', description: 'vehicle' },
      { title: 20, description: 'reg.no' }
    ];
    // this.storage.set('items', this.items);
    // console.log(this.storage.set('items', this.items));
  }
  // Deleting item
  remove(no) {
    (this.bikes).splice(no, 1);
    window.localStorage.clear();
  };

  presentConfirm(){
    let alert = this.alertCtrl.create({
      // window.localStorage.getItem();
      inputs: [
        {
          name: 'Name',
          placeholder: 'Name',
          value:  service.city,
        },
        {
          name: 'Bike Name',
          placeholder: 'Bike Name',
          value: service.bname,
        },
        {
          name: 'Registration Number',
          placeholder: 'Bike Registration Number',
          value: service.no,
        },
      ],
      subTitle: 'Edit Quick Info',
      buttons: ['Save']
    });
    alert.present();
  }
}

#16

@naveesh This error happens:

  1. In development time, showing in your IDE with red squiggles under some word (if so, where in your code this happens, in which line)

  2. In build time, when you try to execute ionic serve, ionic build or ionic run (if so, which line is it).

  3. In runtime (you execute the code successfully and see your page, but an error happens). In this case, you do something (like clicking some button) that triggers the error? Or it happens right after the page is shown. Put some console.log() calls in your code to help discover the cause of the error.

Update

I now see that its in development time. In typescript, you should reference the instance attributes with the this keyword:

value: this.service.city

or

presentConfirm(){
	let service = this.service;
	let alert = this.alertCtrl.create({
	...
}

Doesn’t your IDE show you hints? (in VSCode it shows: [ts] Cannot find name 'service'. Did you mean the instance member 'this.service'?)

Also, after you do that, you might receive the error: [ts] Property 'city' does not exist on type '{}'.. To solve that you could do:

public service: any = {}; // instead of any, it's better to use some interface

(The name service is a bit weird for an object made to contain data. I think data, obj, container fit better in this context. It’s just my opinion, tough. This is not a syntax error or anything of the sort.)

I advise you to study a bit of typescript and the angular syntax, at least the basics, and try some demos (just simple ones, you don’t have to spend much time), otherwise (I think) it will be very difficult for you to create a production ready app. In the angular site they have this tutorial: https://angular.io/tutorial if you feel interested.


#17

thank for the ans…didnt check will check soon.
i have done in different way


#18

@naveesh cool :slight_smile: