简体   繁体   中英

Generic object for different JSON with same structure Angular 2

I have problem with JSON data i have 3 table in my base "dictionary" with same structure and different column names:

{"id":1,"test_1":"test"},{"id":2,"test_1":"lalala"} - first JSON 


{"id":1,"test_2":"****"},{"id":2,"test_2":"afery-t"} - secound JSON

And I want to make one Class in Angular 2

 export class dictionary{

   id:number;
   dictValue:string;

}

Is it posible to cast this differend JSON object to on like this becouse this not working:

res => <dictionary[]>  res.json()

And in Html template i have Json object not class value in NgFor.

 <tr *ngFor="let item of directoryArray">
{{item.test_1}} - i want to have {{item.dictValue}}
</tr>

controller

 directoryArray:dictionary[];
this._httpService.getAll().subscribe(
            data => this.directoryArray = data,
            error => alert(error),
            () => console.log("Done"));

Thanks for help tell me is it possible or i have to change value in base or make different object for all JSONs.

As mentioned, use an Interface:

export interface dictionary { // I would use 'Dictonary' here
   id:number;
   dictValue:string;
}

Not knowing how your getAll function looks like, here's an example of getting the "first" JSON:

getFirstJSON(): Observable<dictionary[]> {
  return this.http.get('the Url')
    .map(res => res.json().map((x:any) => Object.assign({id:x.id,dictValue:x.test_1})))
}

where we use map to set the properties to match your interface.

Then in your component:

directoryArray: dictionary[];

this.service.getFirstJSON()
  .subscribe(data => {
    this.directoryArray = data;
  })

Now we have the properties matching the interface, which can be used in template:

<tr *ngFor="let item of directoryArray">
  <td>{{item.dictValue}}</td>
</tr>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM