1

How do I display this specific JSON using *ngFor?

{
    "status": 0,
    "dallases": [{
        "vehicle_id": 17954,
        "dallassettings": "3",
        "dallasupdated": "False",
        "dallas_list": [{
            "number": 666111222,
            "auth": 3
        }, {
            "number": 666777888,
            "auth": 4
        }, {
            "number": 123454321,
            "auth": 4
        }]
    }
}

vehicle.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Jsonp, Response } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class VehicleService {
    constructor(private http: Http) { }

    getVehicle() {
        return this.http.get('myURL')
            .map(res => res.json());
    }
}

vehicle.component.ts

import { Component, enableProdMode } from '@angular/core';
import { VehicleService } from './vehicle.service';

enableProdMode();

@Component({
  //moduleId: module.id,  
  selector: 'vehicle-json',
  templateUrl: './vehicle.html',
  providers: [VehicleService]
})
export class VehicleComponent {
  //vehicles: Vehicle[];
  vehicles: GeneralVehicle[];

  constructor(private vehicleService: VehicleService) {
    this.vehicleService.getVehicle().subscribe(vehicle => {
      this.vehicles = vehicle;
    });
  }
}

/*interface Vehicle {
  id: number;
  title: string;
  body: string;
}*/
interface GeneralVehicle {
  status: number;
  dallases: Vehicle[];
}

interface Vehicle {
  vehicle_id: number;
  dallassettings: number;
  dallasupdated: string;
  dallas_list: DallasList[];
}

interface DallasList {
  number: number;
  auth: number;
}

When I worked on dummy data it was simply, but this JSON structure is more complex. I tried using Pipe, but I'm not sure if I'm using it correctly.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'keys' })
export class VehiclePipe implements PipeTransform {
    transform(value, args: string[]): any {
        let keys = [];
        for (let key in value) {
            keys.push(key);
        }
        return keys;
    }
}

That's the *ngFor

*ngFor="let vehicle of vehicles | keys"

I'd like to dislay status once, and then repeat all the dallases (Vehicle[]).

3 Answers 3

1

At least you have one error here:

dallassettings: '3' // string

but in your interface you have:

dallassettings: number;

Then if you implement Matthiases implementation, put a *ngIf-statement, since I suspect you get your data async, so view is rendered before data retrieved, which would cause a undefined error.

<div *ngIf="vehicles"> // here!
  <h1>{{ vehicles.status }}</h1>
  <div *ngFor="let vehicle of vehicles.dallases">
    <div>ID: {{vehicle.vehicle_id}}</div>
    <div>Settings: {{vehicle.dallassettings}}</div>
    <div>Updated: {{vehicle.dallasupdated}}</div>
    <div *ngFor="let d of vehicle.dallas_list">
      <div>number: {{d.number}}</div>
      <div>auth: {{d.auth}}</div>
    </div>
  </div>
</div>

EDIT your status is undefined, since you you are using the wrong attribute it should be vehicles.status with "s". When I edited this post, I also added the "s" to the answer, so that it would be correct :)

Sign up to request clarification or add additional context in comments.

3 Comments

I edited the error with number/string. I used yuor code, it displays data now, but still getting error on status. It's not being displayed and returns: EXCEPTION: Cannot read property 'status' of undefined
Yes, it's working. Thank you for you time :) Now, I understand it a bit better. I read way too much stuff, I tried with Pipes and stuff, but the solution was that easy. Have a good day :)
No problem! You have a nice day too! :)
1

You have to loop through 2 ngFor's:

<div *ngFor="let vehicle of vehicles | keys">
    <h1>{{ vehicle.status }}</h1>
    <ul *ngFor="let dallas of vehicle.dallases">
        <li>{{ dallas | json }}</li> //Show the data you want
    </ul>
</div>

3 Comments

Hey Igor, thanks for your response, I implemented your code, the application works w/o any errors, but it doesn't display any data.
@Haseoh Can you please post code where you are populating vehicles?
Check out the question, I submited more of the code.
1

vehicles is an object. I see no need to iterate over the keys with the pipe you proposed. You can access the members you need directly. You should iterate over the dalasses property of vehicles - which is an array. Then display the array member as you require. E.g. with a json pipe to get in text format, you you might also implement custom formatting inside the template through properties.

Example:

<div>
  <h1>{{ vehicle.status }}</h1>
  <div *ngFor="let vehicle of vehicles.dallases">
    <div>ID: {{vehicle.vehicle_id}}</div>
    <div>Settings: {{vehicle.dallassettings}}</div>
    <div>Updated: {{vehicle.dallasupdated}}</div>
    <div *ngFor="let d of vehicle.dallas_list">
      <div>number: {{d.number}}</div>
      <div>auth: {{d.auth}}</div>
    </div>
  </div>
</div>

2 Comments

Hey, I checked your code, it returns an error: Cannot read property 'dallases' of undefined :(
I imagined vehicles is of type GeneralVehicle, because you didn't gave more information about what vehicles actually is. Now that you updated the answer we see that vehicles is of another type - so basically without the information everybody could only guess how to fix it completely. But nevertheless you should have been able to get the general idea from the responses on how to fix your problem.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.