Services & Dependency Injection - Textnotes

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.

  1. providedIn: 'root' → Singleton service available app-wide
  2. providedIn: 'any' → Creates a new instance in each lazy-loaded module
  3. 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:

  1. Root: Singleton, one instance for the whole app (most common)
  2. Platform: Shared instance across multiple Angular apps in the same platform
  3. 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:

  1. Component A updates data in the service
  2. 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

  1. Services contain reusable logic and data
  2. Use CLI to generate services quickly
  3. @Injectable decorator makes services available for DI
  4. Service lifetime can be root, platform, or any
  5. Services help share state and communicate between components