我正在尝试创建已创建Interface的嵌套json对象。我收到错误import { FormsModule } from '@angular/forms';
并说Type of property serservicesAndHeads are incompatible
。我的界面如下:
Property is missing
我的json看起来像这样:
interface Head {
HeadNumber?: string;
HeadDescription?: string;
};
interface ServicesAndHead {
majorService?: string;
subMajorService?: string;
servicesAndHeads:Head[];
}
export interface MyTableItem {
demandNo?: string;
demandName?: string;
servicesAndHeads?:ServicesAndHead;
//servicesAndHeads?:ServicesAndHead[];
}
我也试过嵌套serviceAndHead
const dataItem: MyTableItem =
{
demandNo: 'Demand Number 2',
demandName: 'Animal Husbandary, Livestock, Fisheries and Veterinary Services',
servicesAndHeads: [
{
majorService: 'C-Economic Service',
subMajorService: '(a) Agriculture and Allied Activities',
majorHead: [
{ majorHeadNumber: '3098', majorHeadDescription: 'Animal Husbandry' },
{ majorHeadNumber: '3999', majorHeadDescription: 'Diary Development' },
{ majorHeadNumber: '4902', majorHeadDescription: 'Fisheries' }
]
},
{
majorService: 'C- Capital Account of Economic Services',
subMajorService: '(a) Capital Account of Agriculture and Allied Activities',
majorHead: [
{ majorHeadNumber: '0012', majorHeadDescription: 'Capital Outlay on Animal ' },
{ majorHeadNumber: '3245', majorHeadDescription: 'Capital Outlay on Fisheries' }
]
}
]
}
我如何纠正我的代码以接受所述json。
答案 0 :(得分:3)
定义接口如下:
interface Head {
majorHeadNumber?: string;
majorHeadDescription?: string;
};
interface ServicesAndHead {
majorService?: string;
subMajorService?: string;
majorHead: Head[];
}
export interface MyTableItem {
demandNo?: string;
demandName?: string;
servicesAndHeads?:ServicesAndHead[];
}
这将与您的Json对象兼容。
const dataItem: MyTableItem = {
demandNo: 'Demand Number 2',
demandName: 'Animal Husbandary, Livestock, Fisheries and Veterinary Services',
servicesAndHeads: [
{
majorService: 'C-Economic Service',
subMajorService: '(a) Agriculture and Allied Activities',
majorHead: [
{
majorHeadNumber: '3098',
majorHeadDescription: 'Animal Husbandry'
},
{
majorHeadNumber: '3999',
majorHeadDescription: 'Diary Development'
},
{
majorHeadNumber: '4902',
majorHeadDescription: 'Fisheries'
}]
},
{
majorService: 'C- Capital Account of Economic Services',
subMajorService: '(a) Capital Account of Agriculture and Allied Activities',
majorHead: [
{
majorHeadNumber: '0012',
majorHeadDescription: 'Capital Outlay on Animal '
},
{
majorHeadNumber: '3245',
majorHeadDescription: 'Capital Outlay on Fisheries'
}]
}]
}
答案 1 :(得分:0)
ServicesAndHead
接口将servicesAndHeads
属性定义为必需属性,但dataItem.servicesAndHeads
的数组元素都缺少此属性。它们具有majorHead
属性。或许,你的意思是
interface ServicesAndHead {
majorService?: string;
subMajorService?: string;
majorHead: Head[];
}
如果是这样,您还需要按如下方式调整Head
界面:
interface Head {
majorHeadNumber?: string;
majorHeadDescription?: string;
};