【发布时间】:2021-02-24 07:45:02
【问题描述】:
我是 Angular 新手,我认为我以错误的方式设置了我的模拟数据,这会导致以下错误:
Argument of type '{ "name": string; "refCode": string; "contentId": string; "enabled": boolean; }[]; } | { ...; }' is not assignable to parameter of type 'Item'.
更新了额外的错误信息:
Types of property ... are incompatible.
Type '{ "name": string; "refCode": string; "contentId": string }[]' is not assignable to type 'Item[]'.
Property ... is missing in type '{ "name": string; "refCode": string; "contentId": string;}' but required in type 'Item'.
这是我的 json 文件内容:
{
"data": {
"items": [
{
"obj1": "one",
"obj2": "two",
"obj3": three
},
{
"obj1": "four",
"obj2": "five",
"obj3": siix
"subCategories": [
{
}
]
},
{
"name": "Menu Option 1",
"refCode": "opt1",
"contentId": "0",
"subCategories": [
{}
]
},
{
"name": "Menu Option 2",
"refCode": "opt2",
"contentId": "0"
},
{
"name": "Menu Option 3",
"refCode": "opt3"
}
]
}
}
在我的服务类中,我这样导入它:
import dataItems from './shared/my-items.json';
并像这样声明它:
public menuItems: any;
然后我在我的组件类中迭代这里的项目:
const optionData =
this.itemService.getMenuItems().data.items;
const resource = {};
if (itemData && itemData.length > 0) {
this.items = [];
itemData.forEach(element => {
this.itemService.applyItemName(
element
);
this.items.push(element
});
this.itemService.categories = this.itemss;
}
最后是 applyItemName() 方法,它为给定的项目添加项目及其子项:
public applyItemName(item: Item) {
if (item.subCategories && item.subCategories.length > 0) {
item.subCategories.forEach(subCategory => {
subCategory.parent = category;
this.applyItemName(subCategory);
});
}
}
Item 对象的模型在这里:
export class Category {
public subCategories: Items[];
public contentId: string;
constructor(subCategories: Item[], enabled: boolean, name: string)
{
this.subCategories = subCategories;
this.enabled = enabled;
this.name = name;
}
}
正如我所说,我是新手,我不确定我错过了什么。非常感谢任何提示。
【问题讨论】:
-
该错误应该包含一条消息,说明为什么它通常不能按照“缺少参数 Foo”之类的方式分配。
-
你说得对,谢谢。我会将错误消息的缺失部分添加到帖子中。
标签: angular typescript