-1
votes

Le type 'void' n'est pas attribuable au type 'Recipe []'. erreur dans cette ligne de code this: recettes = this.recipeService.getRecipes ();

Code composant:

import { Recipe } from './recipe.model';
import { EventEmitter } from '@angular/core';
export class RecipeService { 
    recipeSelect = new EventEmitter();

    private recipes: Recipe[] = [
        new Recipe('A Test Recipe', 'This is simply a test', 'https://upload.wikimedia.org/wikipedia/commons/1/15/Recipe_logo.jpeg'),
        new Recipe('Another Test Recipe', 'This is simply a test', 'https://upload.wikimedia.org/wikipedia/commons/1/15/Recipe_logo.jpeg')];
    getRecipes() {
        this.recipes.slice();
    }
}

Un service:

import { Component, OnInit } from '@angular/core';
import { RecipeService } from '../recipe.service';
import { Recipe } from '../recipe.model';

@Component({
    selector: 'app-recipe-list',
    templateUrl: './recipe-list.component.html'
})

export class RecipeListComponent implements OnInit {
    recipes: Recipe[];
    constructor(private recipeService: RecipeService) {
    }

    ngOnInit() {
        this.recipes = this.recipeService.getRecipes();
    }
}


3 commentaires

Vous devez renvoyer this.recipes.slice () depuis la méthode getRecipes (): return this.recipes.slice();


Vous avez oublié d'ajouter une instruction return dans votre méthode getRecipes , donc elle ne renvoie actuellement rien, d'où l'erreur.


Je vous remercie . oui j'avais oublié d'ajouter le type de retour


3 Réponses :


0
votes

Vous devez renvoyer les recettes à partir de la fonction getRecipes

getRecipes(): Recipe[] {
    return this.recipes.slice();
}


0 commentaires

0
votes
getRecipes(): Recipe[] {
    return [...this.recipes];
}
In your example, your service function does not return anything while you are expecting a collection back (this.items).So you have to use the keyword return to achieve this.Furthermore, you are using the slice to return a copy of your local collection, which is a good idea but for the sake of readability and potential performance, I prefer spread operator.See this discussion for the performance reasons : discussion

0 commentaires

0
votes
         return this.recipes.slice();
     }

0 commentaires