In Angular, services are used to encapsulate business logic, data access, and other reusable functionalities. They help keep your components clean and focused on their primary role: managing the user interface. This section will guide you through the process of creating and using services in Angular.
Key Concepts
- Service: A class with a specific purpose, often used to share data and functionality across components.
- Dependency Injection (DI): A design pattern used to implement IoC (Inversion of Control), allowing a class to receive its dependencies from an external source rather than creating them itself.
- Provider: An object that tells the Angular injector how to obtain or create a dependency.
Steps to Create and Use a Service
- Creating a Service
To create a service, you can use the Angular CLI:
This command will generate two files:
my-service.service.ts
my-service.service.spec.ts
(for testing)
- Defining the Service
Open my-service.service.ts
and define your service:
import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class MyService { private data: string[] = []; constructor() {} getData(): string[] { return this.data; } addData(item: string): void { this.data.push(item); } }
- Using the Service in a Component
To use the service in a component, you need to inject it into the component's constructor.
Step-by-Step Example
-
Import the Service: Import the service into your component.
import { Component, OnInit } from '@angular/core'; import { MyService } from './my-service.service';
-
Inject the Service: Inject the service into the component's constructor.
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'] }) export class MyComponent implements OnInit { data: string[]; constructor(private myService: MyService) {} ngOnInit(): void { this.data = this.myService.getData(); } addItem(item: string): void { this.myService.addData(item); this.data = this.myService.getData(); } }
-
Use the Service Methods: Use the service methods within your component to manage data.
<!-- my-component.component.html --> <div> <ul> <li *ngFor="let item of data">{{ item }}</li> </ul> <input #newItem> <button (click)="addItem(newItem.value)">Add Item</button> </div>
- Providing the Service
By default, the @Injectable
decorator with { providedIn: 'root' }
makes the service available application-wide. This is the recommended way to provide services in Angular.
However, you can also provide a service at the component level:
@Component({ selector: 'app-my-component', templateUrl: './my-component.component.html', styleUrls: ['./my-component.component.css'], providers: [MyService] }) export class MyComponent implements OnInit { // Component code here }
Practical Exercise
Exercise: Create and Use a Service
- Create a Service: Create a service named
TaskService
that manages a list of tasks. - Define Methods: Add methods to get tasks, add a task, and remove a task.
- Use the Service: Inject the service into a component and use it to display and manage tasks.
Solution
-
Create the Service:
ng generate service task
-
Define the Service:
// task.service.ts import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root', }) export class TaskService { private tasks: string[] = []; constructor() {} getTasks(): string[] { return this.tasks; } addTask(task: string): void { this.tasks.push(task); } removeTask(task: string): void { this.tasks = this.tasks.filter(t => t !== task); } }
-
Use the Service in a Component:
// app.component.ts import { Component, OnInit } from '@angular/core'; import { TaskService } from './task.service'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { tasks: string[]; constructor(private taskService: TaskService) {} ngOnInit(): void { this.tasks = this.taskService.getTasks(); } addTask(task: string): void { this.taskService.addTask(task); this.tasks = this.taskService.getTasks(); } removeTask(task: string): void { this.taskService.removeTask(task); this.tasks = this.taskService.getTasks(); } }
<!-- app.component.html --> <div> <ul> <li *ngFor="let task of tasks"> {{ task }} <button (click)="removeTask(task)">Remove</button> </li> </ul> <input #newTask> <button (click)="addTask(newTask.value)">Add Task</button> </div>
Summary
In this section, you learned how to create and use services in Angular. Services help encapsulate business logic and data access, making your components cleaner and more focused on the user interface. You also learned how to inject services into components and use their methods to manage data. This foundational knowledge will be crucial as you build more complex Angular applications.
Angular 2+ Course
Module 1: Introduction to Angular
Module 2: TypeScript Basics
- Introduction to TypeScript
- TypeScript Variables and Data Types
- Functions and Arrow Functions
- Classes and Interfaces