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 injectsUserServiceinto 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:

0 Comments
POST Answer of Questions and ASK to Doubt