Book
Submodule 20.3: Services and Dependency Injection - Practice
Submodule 20.3: Services and Dependency Injection - Practice
Completion requirements
View
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 theimport { DISHES } from '../shared/dishes';
.
This means that we also can't use thedishes = 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 itdishService<
, 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 placethis.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.