Ad Code

✨🎆 JOIN MERN, JAVA, PYTHON, AI, DEVOPS, SALESFORCE Courses 🎆✨

Get 100% Placement Oriented Program CLICK to new more info click

Services & Dependency Injection

What is a Service in Angular?

A Service is a class used to share data, logic, or functionality across components.

👉 Common uses:

  • API calls (HttpClient)

  • Business logic

  • Data sharing between components

  • Utility functions

  • Authentication

Syntax to create services:

ng generate service services/user

it creates
import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {

  constructor() { }

  getUsers() {
    return ['Shiva', 'Ram', 'Sita'];
  }
}

What is providedIn: 'root'?

It means:

  • Service is available application-wide

  • Only one instance is created (Singleton)

  • Tree-shakable (removed if not used)

Dependency Injection (DI) in Angular

Dependency Injection means: Angular automatically creates and provides required dependencies.

Instead of doing this:

const userService = new UserService(); ❌ 

Angular does this internally:

constructor(private userService: UserService) {}

Why Dependency Injection is Important?
Without DI: Tight coupling Hard to test Hard to maintain With DI: Loose coupling Easy testing (Mock service) Better architecture Scalable apps

How to use Service in Component?


import { Component } from '@angular/core'; import { UserService } from './services/user.service'; @Component({ selector: 'app-home', standalone: true, template: ` <h2>User List</h2> <div *ngFor="let user of users"> {{ user }} </div> ` }) export class HomeComponent { users: string[] = []; constructor(private userService: UserService) { this.users = this.userService.getUsers(); } }

Types of Service Providers in Angular 21

Root Level (Global Singleton)
@Injectable({ providedIn: 'root' })

Component Level (New Instance per Component)

@Component({

providers: [UserService] })

Each component gets its own instance. Use when: You want isolated state Component-specific logic

Injecting Service using inject()

(Modern Angular 21 Way)

Instead of constructor injection:

import { inject } from '@angular/core'; export class HomeComponent { private userService = inject(UserService); users = this.userService.getUsers(); }

✔ Cleaner
✔ Works well with signals
✔ Recommended in modern Angular





Post a Comment

0 Comments