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 Réponses :
Vous devez renvoyer les recettes à partir de la fonction getRecipes
getRecipes(): Recipe[] { return this.recipes.slice(); }
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
return this.recipes.slice(); }
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éthodegetRecipes
, donc elle ne renvoie actuellement rien, d'où l'erreur.Je vous remercie . oui j'avais oublié d'ajouter le type de retour