-1

Component code:

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

Service:

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();
    }
}
karel
  • 5,489
  • 46
  • 45
  • 50
ALEX
  • 11
  • 3

3 Answers3

0

You need to return the recipes from the getRecipes function

getRecipes(): Recipe[] {
    return this.recipes.slice();
}
Roman Šimík
  • 830
  • 10
  • 24
0
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
Your Code
getRecipes() {
         this.recipes.slice();
     }

Correct Code getRecipes() {

         return this.recipes.slice();
     }