Using the Service

Update the menu.component.ts file to make use of the service as follows:

. . .
import { DishService } from '../services/dish.service';
. . .
export class MenuComponent implements OnInit {
  dishes: Dish[];
  selectedDish: Dish;
  constructor(private dishService: DishService) { }
  ngOnInit() {
    this.dishes = this.dishService.getDishes();
  }
  . . .
}

Notice

  • the import of the DishService from ./services/dish.service. Since we do this import, we no longer need the import { DISHES } from '../shared/dishes';.
     This means that we also can't use the dishes = DISHES; assignment. 
  • constructor(private dishService: DishService) { }.
    With this, we make the service that we have imported available for our components to make use of it. Since we have injected the DishService in the app module, Angular uses the constructor to create a replicate of the DishService , which in this case we have named it dishService<, this is just a name. 
  • dishes: Dish[];. Since we no longer have the DISHES constant, we need to find an alternative way to fetch the information ...
    • ngOnInit() { ... }. This is a life-cycle method. In the
      export class MenuComponent implements OnInit { ... } 
      we see that we have the implementation of the OnInit. 
      So, this is the place this.dishes = this.dishService.getDishes();where you fetch the information. Every time that the user "asks" for this service, angular creates an instant of that DishService and fetch the information needed.