【问题标题】:Generic object for different JSON with same structure Angular 2具有相同结构Angular 2的不同JSON的通用对象
【发布时间】:2017-05-18 08:13:27
【问题描述】:

我的 JSON 数据有问题,我的基本“字典”中有 3 个表,具有相同的结构和不同的列名:

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


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

我想在 Angular 2 中创建一个类

 export class dictionary{

   id:number;
   dictValue:string;

}

是否可以像这样将这个不同的 JSON 对象转换为 on,因为这不起作用:

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

在 Html 模板中我有 Json 对象而不是 NgFor 中的类值。

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

控制器

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

感谢帮助告诉我是否有可能,或者我必须更改基础值或为所有 JSON 制作不同的对象。

【问题讨论】:

  • 你应该使用接口而不是类。这是 Typescript 的功能,而不是 JavaScript 的功能。 Angular 2 默认使用 TypeScript。
  • 是的,我已经改了,谢谢
  • 但是这个必须有所有字段 interface ssda{ test_1: string,test_2: string,}, 还是只有一个月: string??

标签: json angular typescript


【解决方案1】:

如前所述,使用接口:

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

不知道你的 getAll 函数是什么样子的,这里有一个获取“第一个”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})))
}

我们使用map 设置属性以匹配您的界面。

然后在你的组件中:

directoryArray: dictionary[];

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

现在我们有了与接口匹配的属性,可以在模板中使用:

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

【讨论】:

    猜你喜欢
    • 2022-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2019-06-13
    • 1970-01-01
    • 2022-01-20
    • 2020-01-05
    相关资源
    最近更新 更多