angular - Använder mockdata: Typescript kan inte tilldelas typ
Jag är ny på Angular och jag tror att jag har satt upp mina mockdata på fel sätt och att det resulterar i följande fel:
Argument of type '{ "name": string; "refCode": string; "contentId": string; "enabled": boolean; }[]; } | { ...; }' is not assignable to parameter of type 'Item'.
Uppdaterad med ytterligare felmeddelanden:
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'.
Här är innehållet i min json-fil:
{
"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"
}
]
}
}
I min tjänsteklass importerar jag det på det här sättet:
import dataItems from './shared/my-items.json';
Och deklarera det så här:
public menuItems: any;
Sedan itererar jag över objekten här i min komponentklass:
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;
}
Sist är applyItemName()-metoden som lägger till ett objekt och dess barn för ett givet objekt:
public applyItemName(item: Item) {
if (item.subCategories && item.subCategories.length > 0) {
item.subCategories.forEach(subCategory => {
subCategory.parent = category;
this.applyItemName(subCategory);
});
}
}
Modellen för ett Item-objekt är här:
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;
}
}
Som jag sa, jag är ny på det här och jag är inte säker på vad jag missar. Alla tips tas tacksamt emot.
Svar #1
Jag tror att problemet där är att childCategories bör vara valfritt, eftersom det i vissa barn i ditt objekt inte finns. Att lägga till ? vid deklarationen gör det valfritt:
export class Category {
public childCategories?: Category[];
Eller så kan du alltid initialisera childCategories som en tom array
public childCategories: Category[] = [];
