I have one servicio
order-detail.service.ts
that returns the detail of the user's purchase order. When I subscribe to the response from the service, I save the data in an array
orderDetailArray . followed by this, with a foreach
loop and sent the "id_product"array
as a parameter
to the function . The function uses the and saves the corresponding product/book in the bookArray . In conclusion, if the orderDetailArray contains 3 elements, the function should fill the bookArray with 3 products/books. The problem I am having is that even though the orderDetailArray has multiple elements, in the bookArraygetBookById(id_product)
getBookById(id_product)
servicio
book.service.ts
array
getBookById()
I always get only one product/book. I wonder if this problem could be due to having nesting of subscribe
.
herecomponent.ts
orderDetailArray: OrderDetail[] = [];
bookArray: Book[] = [];
ngOnInit(): void {
this.route.params.subscribe((params: Params) => {
const idOrder = params.idOrder;
// obtengo el detalle de la orden de compra
this.orderDetailService.getOrderDetail(idOrder).subscribe(
res => {
this.orderDetailArray = res;
// recorro el array
this.orderDetailArray.forEach(element => {
const idBook = element.id_product.toString();
// Obtengo el libro
this.getBookById(idBook);
})
},
err => console.error('error al obtener el order_detail ' + err)
);
});
}
getBookById(idBook: string){
this.bookService.getBookById(idBook).subscribe(
res => {
this.bookArray = res;
},
err => console.error('error al intentar obtener el libro por id ' + err)
);
}
hereorder-detail.service.ts
getOrderDetail(idOrder: number){
return this.http.get<OrderDetail[]>('http://localhost:4000/getOrderDetail/' + idOrder);
}
book.service.ts
getBookById(id: string){
return this.http.get<Book[]>(`${this.URL_API}/${id}`);
}
Observables are asynchronous operations and, inside your function, you are rewriting the array each time. By not having a resolution order only the last result will be added to the array.