I am making angular application and where I have an empty arrays like these :
orders: Order[];
order_details: Product[];
Then i am making a service call in ngOnInit to store the data into orders array and order_details array,
ngOnInit(): void {
this.getOrders();
}
This is the getOrders() function which is supposed to fetch every Order. Order object has an order_id, product_id list which has all the product ids of the products being ordered and order_time
getOrders() {
this.order_service.getOrderList().subscribe({
next: (data) => {
this.orders = data;
for (let order of this.orders) {
for (let val of order.product_ids) {
this.product_service.getProductById(val).subscribe({
next: (data) => {this.order_details.push(data);}
});
}
}
},
});
console.log(this.order_details);
}
getOrderList() uses api to return all orders
getOrderList(): Observable<Order[]> {
return this.http_client.get<Order[]>(`${this.baseURL}`);
}
getProductById() uses api to return product by id
getProductById(id: number): Observable<Product> {
return this.http_client.get<Product>(`${this.baseURL}/${id}`);
}
The Order object and Product object have fields like
export class Order{
order_id: number;
product_ids: number[];
order_time: String;
}
export class Product{
product_id: number;
product_name: String;
product_image: String;
product_description: String;
product_price: String;
}
I am trying so with the getOrders() function to fetch every order and from every order I access the product id array and find every product by id and then populate the order_details array with these products by using push()
So I was expecting a order_details array with products corresponding to the product_ids mentioned for every order in the orders array
However on doing so, error is being thrown and the order_details array is undefined
ERROR TypeError: Cannot read properties of undefined (reading 'push')