0

i have an Object type of json that I cant read...

this is my json:

body: {
    "111": {
        "name": "name1",
        "status": 10000
    },
    "222": {
        "name": "name2",
        "status": 20000
    },
    "333": {
        "name": "name3",
        "status": 30000
    }
}

and I want to know how to present it in my html?

this is my attempt:

<md-content>
    <h1 align="center">{{title}}</h1>
    <h2>list of items:</h2>
    <div class="list-bg"  *ngFor="#item of items | async">
        ID: {{item.name}} <p></p> Number of Items: {{item.status}}
    </div>
</md-content>

not only that it dosent work, im trying to figure out how to read each line the object id's(those: 111, 222, 333)

this is my model:

  export interface MyModel {
        name: string;
        status: number;
    }

this is my component:

export class MyCmp implements OnInit {
    retJson: Observable<MyModel[]>

    constructor(private _myService: MyService) {};

    public showData(): void {
        this.retJson = this._myService.getData();
    }
}

thanks!

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
jack miao
  • 1,398
  • 1
  • 16
  • 32

2 Answers2

0

You haven't included how you load your json, so I'll write a more general example:

interface MyModel {
    name: string;
    status: number;
}

interface MyResponse {
    body: { [id: string]: MyModel }
}

let response: MyResponse = JSON.parse(RESPONSE_STRING);
Object.keys(response.body).forEach(id => {
    let model = response.body[id];
    console.log(`id: ${ id }, name: ${ model.name }, status: ${ model.status }`);
});

What's missing here is the RESPONSE_STRING, which I'm not sure how you get.
As for the template, I'm not an angular developer but as far as I understand ngFor is used for arrays, and you don't have an array in your json structure.

Nitzan Tomer
  • 155,636
  • 47
  • 315
  • 299
0
  1. ngFor loop only will work for array. Your body json is key value object, so it wouldn't work.
  2. If you want to make it work, it's either:

    • you use an additional pipe to convert key value object to array using pipe, solution discussed here: Iterate over TypeScript Dictionary in Angular 2, then you can use *ngFor="let item of items | async | mapToIterable"

    • Or process it in your ts file, instead of this.retJson = this._myService.getData();, use this._myService.getData().subscribe(x => this.retJson = processToArray(x))

Community
  • 1
  • 1
Jecfish
  • 4,026
  • 1
  • 18
  • 16