Mszarna
Mszarna

Reputation: 113

Two functions that subscribe to the server api, executed in sequence

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);
    });
  }

Upvotes: 0

Views: 32

Answers (1)

tomek550
tomek550

Reputation: 470

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

Upvotes: 1

Related Questions