LABS
COOKIES

Dependency Injection

Git diff Code changes
Chapter Objectives
  • Understand dependency injection

    Learn the fundamentals of dependency injection in Angular.

  • Use services

    Master how to create and inject services in your components.

  • Manage dependencies

    Learn how to properly manage and organize dependencies.

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.

Warning

As you remove this list, the application will stop working (it won’t compile) temporarily because the HTML Template is still expecting a tasks variable.

  1. 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;
  1. Modify the src/app/task-list.component.ts file.
task-list.component.ts
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've 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.