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