Kursinhalt
Introduction to Angular
Introduction to Angular
Service Injection into a Component
You created the TaskService
, which handles storing and managing the task list. However, the service by itself doesn't interact with the user interface. To get the data from the service into the component's template, you need to inject the service into the corresponding component.
Now, you'll see how Angular automatically helps connect services to components using Dependency Injection (DI) and how the service works inside the component.
What is Dependency Injection?
Dependency Injection (DI) is a design pattern where Angular automatically injects the required dependencies (like services) into a component's constructor.
Thanks to DI, components don't create service instances themselves — they simply receive an already created instance. Angular handles delivering the needed objects to whoever requires them.
This works because the service is decorated with:
ts
This decorator tells Angular to create a single instance (singleton) of the service for the entire app and make it available for DI.
Injecting the Service into a Component
Now, let's inject the TaskService
into the TaskListComponent
so it can get the task list and interact with it.
Here's what the component code looks like:
task-list
@Component({ selector: 'app-task-list', imports: [TaskComponent, CommonModule], templateUrl: './task-list.component.html', styleUrls: ['./task-list.component.css'] }) export class TaskListComponent { tasks: Task[] = []; constructor(private taskService: TaskService) { this.tasks = this.taskService.getTasks(); } deleteTask(id: number) { this.taskService.deleteTask(id); this.tasks = this.taskService.getTasks(); } toggleStatus(id: number) { this.taskService.toggleTaskStatus(id); this.tasks = this.taskService.getTasks(); } }
We import the TaskService
, the Task
interface, and other components and modules needed for the template.
In the component constructor, we add the service via Dependency Injection:
task-list
constructor(private taskService: TaskService) { this.tasks = this.taskService.getTasks(); }
Angular automatically injects the needed service instance here. We store it as a private field to use in component methods.
Right after the component is created (inside the constructor), we get the task list. This list is then used in the HTML template.
The methods deleteTask
and toggleStatus
call the service's functions to delete a task or toggle its status, then update the local tasks
array so the UI reflects the changes.
This approach keeps the component simple: it doesn't know how the data is stored or handled — it just asks the service to update it. This separates concerns: components handle the view, and services handle the data.
1. What is Dependency Injection (DI) in Angular?
2. Why do we update this.tasks
after calling deleteTask
or toggleStatus
?
Danke für Ihr Feedback!