🔹 Services are reusable classes that contain business logic, API calls, or shared data.
🔹 They allow us to avoid redundant code by centralizing logic.
🔹 Services can be injected into multiple components using Dependency Injection.
Example of a simple Angular service:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root' // This makes the service available globally
})
export class DataService {
getMessage() {
return 'Hello from DataService!';
}
}
This creates a data.service.ts
file inside the src/app
folder.
Modify data.service.ts
:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class DataService {
private users = ['John', 'Jane', 'Alice', 'Bob'];
getUsers() {
return this.users;
}
}
Import and inject the service into a component:
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';
@Component({
selector: 'app-user',
template: `
<h2>User List</h2>
<ul>
<li *ngFor="let user of users">{{ user }}</li>
</ul>
`,
})
export class UserComponent implements OnInit {
users: string[] = [];
constructor(private dataService: DataService) {}
ngOnInit() {
this.users = this.dataService.getUsers();
}
}
Now, use the <app-user></app-user>
tag in your main template.
🔹 Dependency Injection allows Angular to provide instances of services to components automatically.
🔹 The @Injectable({ providedIn: 'root' })
decorator makes the service globally available.
🔹 DI improves code reusability, testability, and maintainability.
In the above example, the DataService
is injected into the UserComponent
through the constructor:
constructor(private dataService: DataService) { }
Instead of using providedIn: 'root'
, we can specify services in a module or component manually.
Modify app.module.ts
:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent } from './app.component';
import { DataService } from './data.service';
@NgModule({
declarations: [AppComponent],
imports: [BrowserModule],
providers: [DataService], // Register service here
bootstrap: [AppComponent],
})
export class AppModule {}
Providing a Service in a Component
@Component({
selector: 'app-user',
templateUrl: './user.component.html',
providers: [DataService], // Service will be available only in this component and its children
})
export class UserComponent {
constructor(private dataService: DataService) {}
}
✔ Angular Services provide a way to share data and logic across components.
✔ Dependency Injection (DI) allows Angular to manage service instances efficiently.
✔ Using services with DI makes applications modular, scalable, and maintainable.
✔ Services can be provided globally (providedIn: 'root'
) or locally within a module/component.
Understanding Angular Services and DI is essential for building scalable and efficient applications. 🚀