mardi 28 juillet 2020

Angular: .then() block is being executed before my async function

I'm trying to populate my recipeList in my RecipesComponent constuctor but my then() block is being executed before my async GetRecipesService.getRecipes() has finished.

export class RecipesComponent{
    constructor(getRecipesService: GetRecipesService){
        getRecipesService.getRecipes().then(promise=>{
            this.recipeList = getRecipesService.recipes;
            console.log("RecipesComponent recipeList: "+this.recipeList);
        });
        
    }
    recipeList = [];

}

@NgModule()
export class GetRecipesService{
    recipes: any[];
    constructor(private http:HttpClient){
       this.http = http;
    }
    async getRecipes(){
        this.http.get<any[]>('http://localhost:4200/recipes').subscribe(response=>{
            this.recipes = response;
            console.log("getRecipes this.recipes: "+this.recipes);
           
        })
    }
}

In my web browser my console output is:

  1. RecipesComponent recipeList: undefined

  2. getRecipes this.recipes: [object Object],....[object Object]

How do I get my RecipesComponent to wait for getRecipes to finish?




Aucun commentaire:

Enregistrer un commentaire