Dependency injection
- โ๏ธInject the TaskServiceLearn how to inject the TaskService in the TaskListComponent class
- โ๏ธGet the task list referenceLearn how to get the task list reference from the TaskService
Remove the tasks list from the TaskListComponent
The TaskListComponent class is still using its own tasks list. We want it to use the service list instead. The first step is to delete the tasks list from the TaskListComponent class.
๐ Instructions
-
Remove the tasks variable from the
src/app/task-list.component.ts
file.
Inject the TaskService
Our TaskListComponent class needs to use the TaskService to get the tasks list. Angular is using the dependency injection system to provide the TaskService to the TaskListComponent class.
The TaskService class is prefixed by the @Injectable() decorator. This decorator tells Angular that the TaskService class can be injected into other classes.
To do so, you reference the TaskService class in the TaskListComponent class constructor.
We can now use the taskService
variable to access the tasks list and initializes a local variable with the tasks list.
๐ Instructions
-
Update the
src/app/task-list.component.ts
file.
โ๏ธ What you learned
You 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.