Skip to content

Dependency injection

  • โœ”๏ธ
    Inject the TaskService
    Learn how to inject the TaskService in the TaskListComponent class

  • โœ”๏ธ
    Get the task list reference
    Learn 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

  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 implements OnInit {
    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()
    }
    ];
    ngOnInit() {}
    }

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.

constructor(private taskService: TaskService) {}

We can now use the taskService variable to access the tasks list and initializes a local variable with the tasks list.

tasks: Task[] = this.taskService.tasks;

๐ŸŽ“ Instructions

  1. Update 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 implements OnInit {
    tasks: Task[] = this.taskService.tasks;
    constructor(private taskService: TaskService) {}
    ngOnInit() {}
    }

โœ”๏ธ 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.