Creating a Service
Chapter Objectives
- ✔️Create an Angular ServiceLearn how to create a service using the Angular CLI.
Current Situation
You have 2 components in your application: TaskFormComponent and TaskListComponent. The TaskFormComponent is responsible for creating new tasks. The TaskListComponent is responsible for displaying the list of tasks.
Creating a new task means adding it to the task list. However, TaskFormComponent and TaskListComponent are not connected.
We need a third party to manage the items and share them between the two components. This is where Angular services come in!
Angular Services
In Angular, a service is a class that can be used to share data and functionality between different parts of your application. Services are used to encapsulate logic that isn’t directly related to a specific component. This is our situation: tasks are not directly tied to either TaskFormComponent or TaskListComponent but are shared by both components.
For the rest of this course, Angular services will be our main orchestration tool for retrieving, creating, updating, and deleting tasks.
The first objective will be to store the list to make it accessible from both components. By default, Angular services are singletons. This means there is only one instance of the service in the application. As long as you don’t refresh your application, the service will maintain its memory.
Since Angular routing doesn’t refresh the page, the service will keep the task list in memory when switching between TaskFormComponent and TaskListComponent.
Creating a Service
To create a service in Angular, you can use the Angular CLI.
The ng generate
command that you used for components can also be used to generate services.
🎓 Instructions
-
Run the following command in a terminal:
Terminal window ng generate service taskor
Terminal window ng g s taskThis command will create a new file called
task.service.ts
in thesrc/app
folder. -
Open the
task.service.ts
file and add a property to store the task list:task.service.ts import { Injectable } from "@angular/core";import { Task } from "./models/task.model";import { v4 as uuid } from "uuid";@Injectable({providedIn: "root",})export class TaskService {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(),},];}
This list is exactly the same as the one we used in TaskListComponent to display the tasks.
✔️ What You’ve Learned
In this chapter, you learned how to create a service with Angular CLI. Services are used to share data and functionality between different parts of your application. Not only do they help keep your code maintainable by following the DRY principle (“Don’t Repeat Yourself”), but they also help keep your components clean and focused on their main purpose.