I have a question - it may seem obvious to you, but I can't figure it out.
getCategoryID() and getRecipeList()
The first one gets from the API a list of the category array, the second function uses this list to send (n = array length) requests regarding the recipes.
At the end, I want a array: category name recipe name
The problem is that both use subscribe. Due to the fact that they are asynchronous, functions execute too quickly. Tried using await - but then it returns me a Promise. I want the first function to wait for the api to api query and pass the data to the second, not the promise
getCategoriesFromAPI() {
this.apiService.getCategories().subscribe(data => {
console.log(data);
});
}
getRecipesFromAPI() {
this.apiService.getRecipes(categoryID).subscribe(data => {
console.log(data);
});
}
CodePudding user response:
Check out RXJS pipes. They help you with working with different observables. In your case I think you're looking for something like this:
this.apiService.getCategories().pipe(
switchMap((categories) => forkJoin(
categories.map((category) => this.apiService.getRecipes(category.id))
))
).subscribe((recipes) => {
// This should return array of arrays [[recipe, recipe, recipe], [recipe, recipe]]
console.log(recipes);
})
https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin
https://www.learnrxjs.io/learn-rxjs/operators/transformation/switchmap
