I have nested JSON object and I want to store in the Array private categoryModule: CategoryModel[] = []; with Angular 7 HttpClient.
JSON object:
[
{
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' }
]
}
]
My model ProductModel is :
export class ProductModel {
constructor(
public id:number,
public name: string,
public description: string,
public numberOfProduct: number,
public image: string) {}
}
My model 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;
}
}
This is my service for get method :
/** 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', []))
)
}
This is my code component for storing data in Array.
getCagegoryFromServer() {
this.dataStorageServiceServiceta.getCategory().subscribe((category :CategoryModel[]) => {
this.categoryModule = category;
console.log(this.categoryModule[0].products[0] + "milos car");
})
}
I have problem in my categoryModule Array because products is undefined. Obviously products not initialized. Do any know how to fix that?
productsis not initialized because it's namedproductin the JSON. Similarly, your description is nameddescriptio. Fix the JSON. Also, change your classes to interfaces: HttpClient will not create an instance of your classes. If you really need actual instances of your classes, then you need to map the json explictly, and create new instances explicitly.product, useproducts. Instead ofdescriptio, usedescription. What is unclear?