In Angular, services are a fundamental concept used to organize and share code across components, providing a way to centralize functionality that multiple parts of an application can use.
-
Singleton Instances:
- Angular services are usually singleton instances, meaning there's only one instance of a service throughout the application. When injected into different components, they share the same instance.
-
Reusability:
- Services promote reusability by encapsulating specific functionality (such as data manipulation, API calls, or business logic) that can be used across different parts of an application.
-
Separation of Concerns:
- They help maintain a clear separation of concerns by keeping business logic, data access, and other operations separate from the UI components.
-
Dependency Injection:
- Angular's dependency injection system is used to inject services into components or other services, making it easy to use and test services without creating tight coupling between components.
How Services are Created and Used:
-
Creating a Service:
-
Services are typically created as TypeScript classes decorated with
@Injectable()
from@angular/core
. - They often contain methods to perform specific tasks, interact with APIs, manage data, etc.
-
Services are typically created as TypeScript classes decorated with
-
Injecting a Service:
- Services are injected into components or other services via constructor injection.
- Angular's dependency injection system resolves the service dependencies and provides instances of the required services to the components that request them.
Example of a Simple Service:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data: any[] = [];
addData(value: any) {
this.data.push(value);
}
getData() {
return this.data;
}
}
In this example:
-
DataService
is an injectable service. -
It has methods
addData
to add data to an array andgetData
to retrieve the stored data.
Using a Service in a Component:
import { Component } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-example',
template: `
<button (click)="add()">Add Data</button>
<ul>
<li *ngFor="let item of data">{{ item }}</li>
</ul>
`
})
export class ExampleComponent {
data: any[] = [];
constructor(private dataService: DataService) {}
add() {
this.dataService.addData('New Data');
this.data = this.dataService.getData();
}
}
In this component:
-
DataService
is injected intoExampleComponent
via constructor injection. -
The
add()
method of the component uses theDataService
to add and retrieve data.
Services in Angular play a crucial role in building scalable, maintainable, and modular applications by facilitating code reuse and keeping the codebase organized.