У меня есть вложенный объект JSON, и я хочу сохранить его в массиве private categoryModule: CategoryModel[] = [];
с Angular 7 HttpClient
.
JSON-объект:
[
{
id: 1, name: 'Mr. Nice', descriptio: 'dasdad', image: "sada", product: [
{ id: 0, name: 'Milos', descriptio: "sdada", number: 1, image: 'ssad' },
]
},
{
id: 2, name: 'Misko', descriptio: 'dasdad', image: "sada", product: [
{ id: 0, name: 'Milos', descriptio: "sdada", number: 1, image: 'ssad' },
{ id: 1, name: 'Somi', descriptio: "haha", number: 1, image: 'haha' }
]
}
]
Моя модель ProductModel:
export class ProductModel {
constructor(
public id:number,
public name: string,
public description: string,
public numberOfProduct: number,
public image: string) {}
}
Моя модель CategoryModel:
export class CategoryModel {
public id: number;
public name: string;
public description: string;
public image: string;
public products: ProductModel[] ;
constructor(
name: string,
desciption: string,
image: string = null,
products: ProductModel[],
id: number) {
this.id = id;
this.name = name;
this.description = desciption;
this.image = image;
this.products = products;
}
}
Это мой сервис дляget метод:
/** GET heroes from the server */
getCategory(): Observable<CategoryModel[]> {
return this.http.get<CategoryModel[]>(this.cateogryUrl).pipe(
/* map(products => {
return Object.values(products)
}),*/
catchError(this.handleError('getProduct', []))
)
}
Это мой компонент кода для хранения данных в массиве.
getCagegoryFromServer() {
this.dataStorageServiceServiceta.getCategory().subscribe((category :CategoryModel[]) => {
this.categoryModule = category;
console.log(this.categoryModule[0].products[0] + "milos car");
})
}
У меня проблема в массиве categoryModule
, поскольку products
равен undefined
.Очевидно, products
не инициализирован.Кто-нибудь знает, как это исправить?