1

I am fetching recipes from a database (in an Effect - see code below), where each recipe has ingredients. Here is the corresponding Recipe model code:

export class Recipe {
    id_recipe: number;
    name: string;
    image: string;
    difficulty: number;
    category_id: number;
    country_id: number;
    ingredients: Ingredient[];
}

Here is my angular Code

@Effect()
    fetchRecipes = this.actions$.pipe(
        ofType(RecipesActions.FETCH_RECIPES),
        switchMap(() => {
            return this.http.get<Recipe[]>('http://localhost/recipes/get.php',
            {
                params: new HttpParams().set('q', 'SELECT * FROM recipe')
            })
        }),
        map(recipes => {
            return recipes.map(recipe => {
                return {
                    ...recipe,
                    ingredients: this.http.get<Ingredient[]>('http://localhost/recipes/get.php',
                    {
                        params: new HttpParams().set('q', 'SELECT name, amount, units FROM ingredient INNER JOIN recipe_has_ingredient ON ingredient.id_ingredient = recipe_has_ingredient.id_ingredient WHERE recipe_has_ingredient.id_recipe = ' + recipe.id_recipe)
                    })
                }
            })
        }),
        map(recipes => {
            return new RecipesActions.SetRecipes(recipes);
        })
    );

I want to fetch the ingredients based on the recipe id. Currently I get ingredients as an Observable but I want an array. Could somebody help me out here.

lucniner
  • 102
  • 2
  • 2
  • 12
Seiggailion
  • 162
  • 2
  • 2
  • 12
  • 1
    Of bigger concern: Are you allowing raw sql queries to be sent to the server from the client? That looks like a recipe for disaster (pun intended). – Igor Apr 27 '20 at 15:02
  • @Igor I am just practicing Angular and backend is very primitive now because it's not a goal for me now – Seiggailion Apr 27 '20 at 15:14
  • 1
    `I get ingredients as an Observable but I need an array and I just don't know how to fix it.` ← Return either the observable so the caller can Subscribe or call Subscribe yourself on the observable. – Igor Apr 27 '20 at 15:21
  • Does this answer your question? [How do I return the response from an Observable/http/async call in angular?](https://stackoverflow.com/questions/43055706/how-do-i-return-the-response-from-an-observable-http-async-call-in-angular) – Igor Apr 27 '20 at 15:21
  • @Igor i tried to subcribe and get ingredients from subscription but it didn't work. If i return ingredients as Observable how do I use them later? – Seiggailion Apr 27 '20 at 15:26
  • Assign them in your subscribe, it depends on what needs access to the returned results (the caller for example) – Igor Apr 27 '20 at 15:29
  • @Igor, thank you I took ingredients as an Observable and it works now! – Seiggailion Apr 27 '20 at 15:58

0 Answers0