Angular Services · Reusable Logic · Dependency Injection
In Angular, services are used to encapsulate reusable logic that can be shared across components. They commonly handle:
A typical Angular service is a TypeScript class decorated with @Injectable(). It contains methods that can be called from any component where the service is injected.
data.service.ts).@Injectable({ providedIn: 'root' }).This service stores a list of JavaScript frameworks and exposes methods to read and update the list.
// data.service.ts - reusable data service for frameworks
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private data: string[] = ['Angular', 'React', 'Vue'];
constructor() { }
getData(): string[] {
return this.data;
}
addData(item: string) {
this.data.push(item);
}
}
The component injects DataService and displays the frameworks returned by the service.
// app.component.ts - consuming DataService in a component
import { Component, OnInit } from '@angular/core';
import { DataService } from './data.service';
@Component({
selector: 'app-root',
template: `
<h2>Frameworks</h2>
<ul>
<li *ngFor="let item of frameworks">{{ item }}</li>
</ul>
`
})
export class AppComponent implements OnInit {
frameworks: string[] = [];
constructor(private dataService: DataService) { }
ngOnInit() {
this.frameworks = this.dataService.getData();
}
}
If the above component is rendered, the browser will display:
Frameworks
- Angular
- React
- Vue
@Injectable({ providedIn: 'root' }) registers DataService as a singleton service at the root level.constructor(private dataService: DataService).ngOnInit() calls getData() to fetch the list of frameworks and assigns it to the frameworks array.*ngFor to loop through frameworks and render each item in a list.addItem(), removeItem(), and getItems().