In this section, we will delve into the creation and utilization of services in Angular. Services are a fundamental part of Angular applications, providing a way to share data, logic, and functions across different components. They help in keeping the code modular, reusable, and maintainable.
What is a Service?
A service is a class with a well-defined purpose. It is typically used to:
- Encapsulate business logic
- Share data between components
- Handle data retrieval and storage
- Perform operations that are not directly related to the view
Creating a Service
To create a service in Angular, you can use the Angular CLI. The CLI command to generate a service is:
This command will create two files:
my-service.service.ts: The service class file.my-service.service.spec.ts: The test file for the service.
Example: Creating a Data Service
Let's create a simple data service that provides a list of items.
- Generate the Service:
- Implement the Service:
Open data.service.ts and implement the service as follows:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private items: string[] = ['Item 1', 'Item 2', 'Item 3'];
constructor() { }
getItems(): string[] {
return this.items;
}
addItem(item: string): void {
this.items.push(item);
}
}Explanation:
@Injectable({ providedIn: 'root' }): This decorator marks the class as a service that can be injected. TheprovidedIn: 'root'part ensures that the service is available application-wide.getItems(): A method to retrieve the list of items.addItem(item: string): A method to add a new item to the list.
Using a Service in a Component
To use the service in a component, you need to inject it into the component's constructor.
Example: Using DataService in a Component
- Create a Component:
- Inject the Service:
Open item-list.component.ts and modify it as follows:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-item-list',
templateUrl: './item-list.component.html',
styleUrls: ['./item-list.component.css']
})
export class ItemListComponent implements OnInit {
items: string[];
constructor(private dataService: DataService) { }
ngOnInit(): void {
this.items = this.dataService.getItems();
}
addItem(newItem: string): void {
this.dataService.addItem(newItem);
this.items = this.dataService.getItems();
}
}Explanation:
DataServiceis imported and injected into the component's constructor.ngOnInit(): This lifecycle hook is used to initialize the component. It retrieves the list of items from the service.addItem(newItem: string): This method adds a new item using the service and updates the list of items.
- Update the Template:
Open item-list.component.html and update it as follows:
<div>
<h2>Item List</h2>
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
<input #newItem type="text" placeholder="New Item">
<button (click)="addItem(newItem.value); newItem.value=''">Add Item</button>
</div>Explanation:
*ngFor: A structural directive to loop through the list of items and display them.#newItem: A template reference variable to capture the input value.(click): An event binding to call theaddItemmethod when the button is clicked.
Practical Exercise
Exercise: Create and Use a Logging Service
- Create a Logging Service:
Generate a new service called logging.
- Implement the Logging Service:
Open logging.service.ts and implement the service as follows:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LoggingService {
log(message: string): void {
console.log(message);
}
}- Use the Logging Service in a Component:
Inject the LoggingService into a component and use it to log messages.
import { Component, OnInit } from '@angular/core';
import { LoggingService } from '../logging.service';
@Component({
selector: 'app-log-demo',
templateUrl: './log-demo.component.html',
styleUrls: ['./log-demo.component.css']
})
export class LogDemoComponent implements OnInit {
constructor(private loggingService: LoggingService) { }
ngOnInit(): void {
this.loggingService.log('LogDemoComponent initialized');
}
logMessage(message: string): void {
this.loggingService.log(message);
}
}- Update the Template:
Open log-demo.component.html and update it as follows:
<div> <h2>Log Demo</h2> <input #logMessage type="text" placeholder="Log Message"> <button (click)="logMessage(logMessage.value); logMessage.value=''">Log Message</button> </div>
Solution:
- The
LoggingServiceis created and used to log messages to the console. - The
LogDemoComponentuses the service to log a message when the component is initialized and when the button is clicked.
Summary
In this section, we learned how to create and use services in Angular. We covered:
- What a service is and its purpose.
- How to create a service using the Angular CLI.
- How to implement and use a service in a component.
- A practical exercise to reinforce the concepts.
Services are a powerful feature in Angular that help in creating modular, reusable, and maintainable code. In the next section, we will explore dependency injection in more detail, which is a key concept for using services effectively.
Angular Course
Module 1: Introduction to Angular
- What is Angular?
- Setting Up the Development Environment
- Angular Architecture
- First Angular Application
Module 2: Angular Components
- Understanding Components
- Creating Components
- Component Templates
- Component Styles
- Component Interaction
Module 3: Data Binding and Directives
- Interpolation and Property Binding
- Event Binding
- Two-Way Data Binding
- Built-in Directives
- Custom Directives
Module 4: Services and Dependency Injection
Module 5: Routing and Navigation
Module 6: Forms in Angular
Module 7: HTTP Client and Observables
- Introduction to HTTP Client
- Making HTTP Requests
- Handling HTTP Responses
- Using Observables
- Error Handling
Module 8: State Management
- Introduction to State Management
- Using Services for State Management
- NgRx Store
- NgRx Effects
- NgRx Entity
Module 9: Testing in Angular
Module 10: Advanced Angular Concepts
- Angular Universal
- Performance Optimization
- Internationalization (i18n)
- Custom Pipes
- Angular Animations
