Currently, I am utilizing Angular 13 with TypeScript. Within my Service class, there is a method that carries out a get request to a REST API:
getProduct(productId): Observable<Product> {
const productUrl = `http://localhost/api/products/${productId}`;
return this.httpClient.get<Product>(productUrl);
}
Additionally, I have an array of product IDs:
let productIds: string[] = ['1', '2', '3', '4', ...];
My goal is to invoke the getProduct() method for all product IDs and then perform another action once all the calls have completed. I have tried utilizing a for loop to call getProduct() for each ID, but the asynchronous nature of the code means that the code following the loop executes immediately, rather than waiting for all products to finish processing.
Here is the code snippet for calling getProduct():
async getAllProducts() {
for(const productId of this.productIds) {
let product : Product = await this.productService.getProduct(productId).toPromise();
.
.
// perform additional actions
}
}
There is another method in the same class:
foo() {
this.getAllProducts();
// I would like the remaining code here to only run once getAllProducts() has completed its tasks
}
Any assistance is greatly appreciated.