angular - Používání mock dat: Typescript nelze přiřadit k typu
Jsem nový v Angularu a věřím, že jsem nastavil své falešné údaje špatným způsobem, což má za následek následující chybu:
Argument of type '{ "name": string; "refCode": string; "contentId": string; "enabled": boolean; }[]; } | { ...; }' is not assignable to parameter of type 'Item'.
Aktualizováno s dalšími chybovými zprávami:
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'.
Tady jsou obsahy mého json souboru:
{
"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"
}
]
}
}
Ve své servisní třídě ji importuji takto:
import dataItems from './shared/my-items.json';
A deklarujte to takto:
public menuItems: any;
Pak procházím položky zde ve své třídě komponenty:
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;
}
Nakonec je zde metoda applyItemName(), která přidá položku a její podřízené položky pro danou položku:
public applyItemName(item: Item) {
if (item.subCategories && item.subCategories.length > 0) {
item.subCategories.forEach(subCategory => {
subCategory.parent = category;
this.applyItemName(subCategory);
});
}
}
Model pro objekt Položka je zde:
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;
}
}
Jak jsem řekl, jsem v tom nový a nejsem si jistý, co mi chybí. Jakékoliv tipy jsou velice vítány.
Odpověď č. 1
Myslím, že problém je v tom, že childCategories by mělo být volitelné, protože u některých dětí ve vašem objektu není přítomno. Přidání ? při deklaraci to udělá volitelným:
export class Category {
public childCategories?: Category[];
Nebo můžete vždy inicializovat childCategories jako prázdné pole
public childCategories: Category[] = [];
