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

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

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

  private userName: string = "Shiva";

  constructor() { }

  getUserName() {
    return this.userName;
  }

  setUserName(name: string) {
    this.userName = name;
  }
}


providedIn: 'root' → Service is Singleton (one instance in entire app)

Step 2: Inject Service in Component

import { Component } from '@angular/core';
import { UserService } from '../services/user.service';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html'
})
export class HomeComponent {

  name: string = '';

  constructor(private userService: UserService) { }

  ngOnInit() {
    this.name = this.userService.getUserName();
  }

  changeName() {
    this.userService.setUserName("Rahul");
    this.name = this.userService.getUserName();
  }
}

home.component.html

<h2>User Name: {{ name }}</h2>
<button (click)="changeName()">Change Name</button>


Step 2: Create API Service

ng generate service services/product

📌 product.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

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

private apiUrl = 'https://jsonplaceholder.typicode.com/posts';

constructor(private http: HttpClient) {}

getProducts(): Observable<any> {
return this.http.get(this.apiUrl);
}
}

📌 Step 3: Inject in Component

import { Component } from '@angular/core';
import { ProductService } from '../services/product.service';

@Component({
selector: 'app-products',
template: `
<h3>Product List</h3>
<ul>
<li *ngFor="let item of products">
{{ item.title }}
</li>
</ul>
`
})
export class ProductsComponent {

products: any[] = [];

constructor(private productService: ProductService) {}

ngOnInit() {
this.productService.getProducts()
.subscribe(data => {
this.products = data;
});
}
}

3️⃣ Real Example – Authentication Service (Login)

📌 auth.service.ts

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

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

private isLoggedIn = false;

login(username: string, password: string) {
if (username === 'admin' && password === '1234') {
this.isLoggedIn = true;
}
}

logout() {
this.isLoggedIn = false;
}

isAuthenticated() {
return this.isLoggedIn;
}
}

📌 Use in Multiple Components

constructor(private authService: AuthService) {}

login() {
this.authService.login('admin', '1234');
}

✅ This is Dependency Injection
Angular automatically injects UserService into constructor.
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