Skip to content

Service creation

  • βœ”οΈ
    Create an Angular service
    Learn how to create a service in Angular using the Angular CLI.

The problem

You have 2 components in the 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 implies adding it to the list of tasks. But the TaskFormComponent and the TaskListComponent are not connected.

You need a third party to manage the tasks and share them between the two components. That’s what Angular Services come in!

Angular services

In Angular, a service is a class that can be used to share data and functionality across different parts of your application. Services are used to encapsulate the logic that is not directly related to a specific component. That’s our situation: the tasks are not directly related to the TaskFormComponent or the TaskListComponent.

For the rest of this course, Angular services will be our main orchestration tool to retrieve, create, update and delete tasks.

The first goal will be to store the list to make it accessible from both components. By default, Angular services are singletons. This means that there is only one instance of the service in the application. As long as you do not refresh your application, the service will keep its memory.

As Angular routing does not refresh the page, the service will keep the list of tasks in memory by switching between the TaskFormComponent and the TaskListComponent.

Create a service

To create a service in Angular, you can use the Angular CLI. The ng generate command you used for components can also be used to generate services by using the service keyword in place of component.

πŸŽ“ Instructions

  1. Run the following command in a terminal:

    Terminal window
    ng generate service task

    This command will create a new file called task.service.ts in the src/app folder.

  2. Open the task.service.ts file and add a property to store the list of tasks:

    task.service.ts
    import { Injectable } from '@angular/core';
    import { Task } from './models/task.model';
    @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 one we used in the TaskListComponent to display the tasks.

βœ”οΈ What you learned

In this chapter, you learned how to create a service with Angular CLI. Services are used to share data and functionality across different parts of your application. Not only do they help to keep your code DRY, but they also help to keep your components clean and focused on their main purpose.