angular - 使用模拟数据:Typescript 不可分配给类型
问题描述
我是 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;
}
}
正如我所说,我是新手,我不确定我错过了什么。非常感谢任何提示。
解决方案
我认为存在的问题childCategories
应该是可选的,因为在您的对象中的某些孩子中它不存在。添加?
at 声明将使其成为可选:
export class Category {
public childCategories?: Category[];
或者你总是可以将 childCategories 初始化为一个空数组
public childCategories: Category[] = [];
推荐阅读
- python - 强制 dask to_parquet 写入单个文件
- angular - 在打开日历之前,日期选择器值不会在视图中更新
- tensorflow-federated - 尝试“tff.learning.assign_weights_to_keras_model”方法时出错
- c++ - 在 C++ 中,给定字符串向量,如何在编译时填充映射?
- javascript - 如何将数据从 javascript 函数传递到重定向页面?
- javascript - 为什么leaflet.js 在map.addlayer(layer) 上添加了不止一层?
- javascript - 使用 CefSharp 获取 xhtml 后停止内容加载
- java - 如何避免这种情况下的instanceof?
- visual-studio-code - VSCode 冻结并停止响应
- java - Log4j2:如何说服它 log4j-core.jar 的类确实存在?