Dependency Injection
Chapter Objectives
- ✔️Inject TaskServiceLearn how to inject TaskService into the TaskListComponent class.
- ✔️Get the tasks list referenceLearn how to get the tasks list reference from TaskService.
Remove the tasks list from TaskListComponent
The TaskListComponent class is still using its own tasks list. You need it to use the service’s list instead. The first step is to remove the tasks list from the TaskListComponent class.
🎓 Instructions
-
Remove the tasks variable from the
src/app/task-list.component.ts
file.task-list.component.ts @Component({selector: "app-task-list",templateUrl: "./task-list.component.html",styleUrls: ["./task-list.component.css"],})export class TaskListComponent {tasks: Task[] = [{id: uuid(),title: "Task 1",description: "Description of task 1",createdAt: new Date(),},{id: uuid(),title: "Task 2",description: "Description of task 2",createdAt: new Date(),},];}
Inject TaskService
Your TaskListComponent class needs to use TaskService to get the tasks list. Angular uses the dependency injection system to provide TaskService to the TaskListComponent class.
The TaskService class is prefixed with the @Injectable() decorator. This decorator tells Angular that the TaskService class can be injected into other classes.
To do this, you will reference the TaskService class in the TaskListComponent class constructor.
constructor(private taskService: TaskService) {}
You can now use the taskService variable to access the tasks list and initialize a local variable with the tasks list.
tasks: Task[] = this.taskService.tasks;
🎓 Instructions
- Modify the
src/app/task-list.component.ts
file.
import { Component } from "@angular/core";
import { TaskService } from "../task.service";
@Component({ selector: "app-task-list", templateUrl: "./task-list.component.html", styleUrls: ["./task-list.component.css"],})export class TaskListComponent { tasks: Task[] = this.taskService.tasks;
constructor(private taskService: TaskService) {}}
✔️ What you have learned
You have learned how to inject a service into a component using Angular’s dependency injection system. It makes your service accessible in the component and allows you to use the service’s methods and properties.