Services & Dependency Injection
In Angular, services are used to write reusable business logic, share data between components, or handle tasks like API calls. Dependency Injection (DI) allows Angular to provide a service to a component automatically.
1. Creating Services
Use Angular CLI to generate a service:
ng generate service user
# or
ng g s user
This creates:
user.service.ts → Service logic
user.service.spec.ts → Testing file
Example user.service.ts:
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserService {
users: string[] = ['John', 'Jane', 'Mike'];
getUsers() {
return this.users;
}
addUser(name: string) {
this.users.push(name);
}
}
2. Injectable Decorator
The @Injectable decorator makes a class available for DI.
- providedIn: 'root' → Singleton service available app-wide
- providedIn: 'any' → Creates a new instance in each lazy-loaded module
- providedIn: 'platform' → Shared instance across multiple apps on the same platform
@Injectable({
providedIn: 'root'
})
export class UserService { }
3. Service Lifetime
Service instances depend on how they are provided:
- Root: Singleton, one instance for the whole app (most common)
- Platform: Shared instance across multiple Angular apps in the same platform
- Any: New instance for each lazy-loaded module
4. Using Services in Components
Inject the service in a component constructor:
import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-home',
templateUrl: './home.component.html'
})
export class HomeComponent implements OnInit {
users: string[] = [];
constructor(private userService: UserService) { }
ngOnInit() {
this.users = this.userService.getUsers();
}
addUser(name: string) {
this.userService.addUser(name);
this.users = this.userService.getUsers();
}
}
home.component.html
<ul>
<li *ngFor="let user of users">{{ user }}</li>
</ul>
<input #nameInput placeholder="Enter name">
<button (click)="addUser(nameInput.value)">Add User</button>
5. Shared State Using Services
Services can store shared data accessible by multiple components:
- Component A updates data in the service
- Component B automatically receives the updated data (if using observables or the same service instance)
Example using a simple array (as above) or a BehaviorSubject for reactive updates.
Summary
- Services contain reusable logic and data
- Use CLI to generate services quickly
@Injectabledecorator makes services available for DI- Service lifetime can be root, platform, or any
- Services help share state and communicate between components