In my code, I have a property called
category = <CategoryModel>{};
. The CategoryModel model looks like this:
export class CategoryModel {
public name: string;
public description: string;
public image: string;
public products?: ProductModel[];
constructor(name: string, desciption: string, image: string = null, products: ProductModel[]) {
this.name = name;
this.description = desciption;
this.image = image;
this.products = products;
}
}
I am trying to store the category
in an Array named
categoryList: CategoryModel[] = [];
using the following code this.categoryList.push(this.category);
. But I encountered an error saying ERROR TypeError: Cannot read property 'push' of null
.
This is a post method where I intend to save the category
in the array and then send it to the server.
export class AdminComponent implements OnInit {
category = <CategoryModel>{};
categoryList: CategoryModel[] = [];
categoryProduct: ProductModel[];
...
constructor(...) { }
ngOnInit() {
this.getCategory();
this.initForm();
console.log(this.categoryList);
}
...
getCategory() {
this.dataStorageServiceService.getCategory()
.subscribe(
(cateogrys: CategoryModel[]) => {
this.categoryList = cateogrys;
console.log(this.categoryList)
}
);
}
storeCategoryList() {
const nameCategory = this.categoryForm.value.name;
const descriptionCategory = this.categoryForm.value.category;
this.category.name = nameCategory;
this.category.description = descriptionCategory;
console.log(this.category);
this.categoryList.push(this.category);
this.dataStorageServiceService.storeCategoryList(this.categoryList).subscribe(
(category: CategoryModel) => {
category = this.category
this.categoryList.push(category)
console.log(this.categoryList)
}
)
}
...