miércoles, 26 de octubre de 2016

Bind json data to html table with Angular 2

Here I come again!

In this example I will show how to bind a JSON file with an html table with Angular2 (the new version of AngularJS, but with Typescript).

Here you can see the demo (click the Project link button).

We need a Service Object and a Component Object and I'm going to use Angular-cli to create them.

First of all, take a look to Service class:

(we will create them with: ng generate service [my.servicename.service])

And I make the next modifications:



The Service returns an Observable of any type, that makes asyncron the call from the Component. So you can extend the code by using any structure of JSON file and making some modifications.

Now I will show you the Component, that we will create with the instruction (ng generate component [componentname.component]):

 

The Component will call our Service and save the information of the JSON file.

Now comes the HTML file and the CSS file:



Here you can see the use of ngFor, the declaration of a variable with "let" and the attribute "async" that makes asyncron our request.

The JSON file will look like this. You can put the attributes you want, but it's important that the HTML file have the sames name of the JSON file's attributes.



And finally, I can show you the structure of the project that has been done with Angular-Cli, as I said in the beginning.



This is my Git Repository where I push this project and you can get it: https://github.com/davidmartinezros/bind-json-array-to-html-table.

Thanks for reading me, I hope it will help you!

Try it and have fun!

14 comentarios:

  1. Hi David,

    What if I have the same JSON file but with address object inside like:

    {"id":"1", "name":"Ricardo", "address":{"street":"main Street","city":"NewYork"}, "age":"30"}

    How do I show the street name in my view?

    ResponderEliminar
  2. Hi Ricardo,

    Interesting question, I'm going to explain you how to do.

    The json file is a structure file data, with parents and childs, like an xml.

    So to obtain the data from a json file, you have to do that:

    data.json().address.street -> this show the street name
    data.json().address.city -> this show the city name

    And to load the json file, I explain in the new article in this blog: link

    I hope I explain correctly and you understand the way.

    For any more question, don't doubt to contact me.

    Try it and have fun!

    David

    ResponderEliminar
  3. what if i have a JSON URL rather than a file so how do i get the data from that url and display the whole data in a table?

    ResponderEliminar
    Respuestas
    1. Is in the same way.

      With this.http.get(url) you can load a json file or a url json file.

      You only have to substitute the variable url for 'http://yourdomain.com/file.json'.

      I hope I explain!

      David

      Eliminar
  4. Thank you David this is what i want. thank you again for this.

    ResponderEliminar
    Respuestas
    1. Thanks to you for the comment.

      If you are interested in contact me, send my an email at davidnezan@gmail.com.

      Have a nice day!

      David

      Eliminar
  5. hi david,

    What if I have the same JSON file but with address object inside like:

    {"id":"1", "name":"Ricardo", "address":{"street":"main Street","city":"chennai"}, "age":"32"}

    How do I show the street name in my view?

    give example program

    ResponderEliminar
    Respuestas
    1. For getting the street attribute, you have to do this:

      var json: Observable = this.http.get('json_rute_file')
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error));

      console.log('json.address.street:' + json.address.street);

      Eliminar
  6. hi David,

    What if I have JSON file like this below i have mentioned:
    {
    "Market": [{
    "id": 1,
    "name": "gard",
    "description": "gard",
    "nbrOfCompartments": 3,
    "compartmentHoldingWeightInGrams": 500,
    "sellingPrice": 625.00,
    "NutsAndDriedFruits": [{
    "id": 1,
    "name": "kjjh",
    "description": "kjjh",
    "type": "Nut",
    "weightInGrams": 87,
    "sellingPrice": 444.00,
    "inStock": 1
    },
    {
    "id": 2,
    "name": "apple",
    "description": "apple",
    "type": "DriedFruit",
    "weightInGrams": 450,
    "sellingPrice": 1290.00,
    "inStock": 1
    },
    {
    "id": 3,
    "name": "goyii",
    "description": "goyii",
    "type": "Nut",
    "weightInGrams": 506,
    "sellingPrice": 129.00,
    "inStock": 1
    }],

    [{
    "id": 2,
    "name": "gard",
    "description": "gard",
    "nbrOfCompartments": 3,
    "compartmentHoldingWeightInGrams": 500,
    "sellingPrice": 625.00,
    "NutsAndDriedFruits": [{
    "id": 1,
    "name": "kjjh",
    "description": "kjjh",
    "type": "Nut",
    "weightInGrams": 87,
    "sellingPrice": 444.00,
    "inStock": 1
    },
    {
    "id": 2,
    "name": "apple",
    "description": "apple",
    "type": "DriedFruit",
    "weightInGrams": 450,
    "sellingPrice": 1290.00,
    "inStock": 1
    },
    {
    "id": 3,
    "name": "goyii",
    "description": "goyii",
    "type": "Nut",
    "weightInGrams": 506,
    "sellingPrice": 129.00,
    "inStock": 1
    }]

    ..................etc.,

    }


    How do i show the Market Id,name,Description...etc in my view

    give Some Example program

    ResponderEliminar
    Respuestas
    1. For getting the Market Id, you have to do this:

      var json: Observable = this.http.get('json_rute_file')
      .map((res:Response) => res.json())
      .catch((error:any) => Observable.throw(error.json().error));

      console.log(json);

      Print the json structure and iterate and navigate for the node you want to show.

      The json structure is not correctly. Verify it first.

      You have an array into another array, but the second array is not closed.

      Eliminar
  7. Hi David

    Can you pls. add edit/delete button in this code, so that I can understand how to add button in angular

    ResponderEliminar
  8. Hello , This is Abdullah From Bangladesh . I am working on this json data .
    https://webmppcapstone.blob.core.windows.net/data/itemsdata.json

    I have this model to map with the class :
    //Category
    export class Categories {
    catname: string ;
    subcategories : Subcategories[] ;
    constructor() {
    }

    }
    //subcategory

    export class Subcategories {
    subcatename: string ;
    items : Product[] ;
    constructor() {
    }

    }

    //product
    export class Product {
    name: string ;
    description: string ;
    price: number ;
    imagelink: string ;
    rating : string ;
    stock : string ;
    categoryname: string ;
    subcategoryname: string ;
    constructor() {
    }

    }

    but I have not been able to populate the html file from my json object .
    this is the part of my api.. so far no visible error . still no output


    public getProductSummary(): Observable {
    // get users from api
    var json = this.http.get(API_URL )//, options)
    .map(this.extractData)
    .catch(this.handleError);

    console.log(json);
    return json ;
    }


    private handleError (error: any) {
    let errMsg = error.message || 'Server error';
    console.error(errMsg); // log to console instead
    return Observable.throw(errMsg);
    }




    private extractData(res: Response) {
    if (res.status < 200 || res.status >= 300) {
    throw new Error('Bad response status: ' + res.status);
    }
    let body = res.json();
    return body.data
    }
    .. Can You help me to sort this issue


    ResponderEliminar
  9. Hi I am calling json data from the service and printing in the html but while subscribe in component I want to print it in the console.. but unable to do that please help me



    data: RowData[]= [];
    private errorMessage:any = '';
    private subscription: ISubscription;
    classtititle: any;




    constructor(private _http:Http, private _sampleService:sampleService) {

    }

    ngOnInit() {

    this.subscription = this._sampleService.getproducts().subscribe((res) => this.data = res, error => this.errorMessage = error);

    }

    ResponderEliminar
    Respuestas
    1. Hi Pravallika,

      First of all, your service must return an Observable.
      And you don't need the ISubscription.

      In this code, you have an example:

      https://github.com/davidmartinezros/myyme/blob/master/src/app/unity-get/unity-get.component.ts

      You have to do something like this:

      this.robotService.getUnity(this.modelUser.id, 'AAA', this.concept)
      .subscribe(res => this.modelUnity = res);

      Where modelUnity will have the response of the service call.

      Have a nice day!

      David

      Eliminar