I've been attempting to loop through an array of objects in TypeScript, but encountered the following error:
ERROR Error: Uncaught (in promise): TypeError: Cannot read property 'forEach' of undefined
TypeError: Cannot read property 'forEach' of undefined
Below you can find the code snippet in question:
export class Data{
products: Product[];
constructor(
private route: ActivatedRoute,
private router: Router,
private _http:HttpClient){
this.getProducts().subscribe(products=> this.products= products);
}
ngOnInit(){
let productId = this.route.snapshot.params['id'];
this.id= productId;
this.getProducts();
this.findProduct();
}
findProduct(){
this.products.forEach((product,index) =>{
console.log(product.name);
console.log(index);
})
}
getProducts(){
return this._http.get<Product[]>('../src/assets/product-data.json');
}
I have tried multiple solutions without success.
I made sure to import BrowserModule
and CommonModule
into my module.
Any suggestions on how I can resolve this issue would be greatly appreciated.
Thank you