Services in Angular
In Angular, a service is a class with a specific purpose. It's used to organize and share code across your application. Services are essential for tasks that don't directly relate to the view, such as data fetching, logging, or business logic.
Services allow you to separate concerns and make your code more modular and reusable. They are typically used for:
- Fetching data from a server.
- Sharing data between components.
- Implementing business logic.
- Logging.
- Performing calculations.
Creating a Service
To create a service, you use the @Injectable
decorator. This decorator tells Angular that the class can be injected as a dependency.
Example 1: Simple Data Service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
getData(): string[] {
return ['Item 1', 'Item 2', 'Item 3'];
}
}
Explanation:
@Injectable({ providedIn: 'root' })
: Makes the service available throughout the application.getData()
: A method that returns an array of strings.
Example 2: Logging Service
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class LoggingService {
log(message: string): void {
console.log('LOG: ${message}');
}
}
Explanation:
log(message: string)
: A method that logs a message to the console.
Using a Service
To use a service, you inject it into a component or another service using dependency injection.
Example: Injecting and Using a Service
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
import { LoggingService } from './logging.service';
@Component({
selector: 'app-my-component',
template: `
<ul>
<li *ngFor="let item of items">{{ item }}</li>
</ul>
`
})
export class MyComponent implements OnInit {
items: string[];
constructor(private dataService: DataService, private loggingService: LoggingService) {}
ngOnInit() {
this.items = this.dataService.getData();
this.loggingService.log('Data loaded.');
}
}
Explanation:
constructor(private dataService: DataService, private loggingService: LoggingService)
: Injects theDataService
andLoggingService
into the component.ngOnInit()
: Calls thegetData()
method of theDataService
and thelog()
method of theLoggingService
.
Shared Services
A shared service is a service that is used by multiple components throughout your application. It acts as a central point for data sharing and communication. When a service is provided at the root level (providedIn: 'root'
), it becomes a singleton, meaning there's only one instance of the service shared across the entire application.
Benefits of Shared Services
- Data Sharing: Allows components to share data without direct parent-child relationships.
- Code Reusability: Centralizes common functionality.
- Maintainability: Makes your code easier to manage and update.
If you have any questions, feel free to ask. Thank you for reading!
If you have any query or question, please contact through below form. Our team will be in touch with you soon.
Please provide your valueable feedback or suggession as well.