Typescript 将响应数据强制转换为包含映射的类

Typescript 将响应数据强制转换为包含映射的类,typescript,Typescript,我从后端以这种形式接收一些json数据。字段“labels”应该是字符串的映射(这是后端处理它的方式): 收到的json数据: 0:对象{标签:对象{group1:“开发人员”}名称:“test1”} 1:Object{labels:Object{group2:“testers”}name:“test2”} 在我的typescript代码中,我有一个名为Group的类。当我收到这个响应时,我尝试使用 this.groups = <Group[]>data 组件 ngOnInit()

我从后端以这种形式接收一些json数据。字段“labels”应该是字符串的映射(这是后端处理它的方式):

收到的json数据:

0:对象{标签:对象{group1:“开发人员”}名称:“test1”} 1:Object{labels:Object{group2:“testers”}name:“test2”}

在我的typescript代码中,我有一个名为Group的类。当我收到这个响应时,我尝试使用

this.groups = <Group[]>data
组件

ngOnInit() {

  this.groupsService.getGroups().subscribe(data => {

       this.groups = <Group[]>data
      console.log("Groups",this.groups)
    }
      , err => { console.log(err) })

  }

export class Group {
    name:string;
    users?:string[];
    labels?:Map<string, string>
}
ngOnInit(){
this.groupsService.getGroups().subscribe(数据=>{
this.groups=数据
console.log(“Groups”,this.Groups)
}
,err=>{console.log(err)})
}
导出类组{
名称:字符串;
用户?:字符串[];
标签?:地图
}

Map
是JavaScript类。JSON没有这种类型,这就是为什么
标签
显示为
对象
。所以你有两个选择:

  • 从对象
    标签
  • 标签的类型更改为
    {[label:string]:string}
    ,并将其用作
    对象
构建地图可能如下所示:

this.groups = (<any[]>data).map(group => {
   let labelsObject = group.labels;
   group.labels = new Map<string, string>();

   if (labelsObject) {
     Object.keys(labelsObject).forEach(key => group.labels.set(key, labelsObject[key]));
   }

   return <Group>group;
});
this.groups=(数据).map(组=>{
让labelsObject=group.labels;
group.labels=新映射();
if(标签对象){
Object.keys(labelsObject).forEach(key=>group.labels.set(key,labelsObject[key]);
}
返回组;
});
this.groups = (<any[]>data).map(group => {
   let labelsObject = group.labels;
   group.labels = new Map<string, string>();

   if (labelsObject) {
     Object.keys(labelsObject).forEach(key => group.labels.set(key, labelsObject[key]));
   }

   return <Group>group;
});