Skip to content
Angular

Services & Dependency Injection

Create an injectable service and consume it in a component.

By EZ4Code Team
servicedependency-injection

Code

import { Injectable, inject, Component } from "@angular/core";
import { NgFor } from "@angular/common";

@Injectable({ providedIn: "root" })
export class UserService {
  private users = ["Alice", "Bob"];
  getAll() { return [...this.users]; }
  add(name: string) { this.users.push(name); }
}

@Component({
  selector: "app-user-list",
  standalone: true,
  imports: [NgFor],
  template: "<li *ngFor=\"let u of users\">{{ u }}</li>"
})
export class UserListComponent {
  private svc = inject(UserService);
  users = this.svc.getAll();
}

Explanation

Services encapsulate shared logic and state. The @Injectable decorator with providedIn root registers a singleton across the app. Components obtain instances via dependency injection using the inject() function or constructor parameters.

More Angular Snippets