Services Explained - Dependency Injection, Reusable Logic

What is a Service in Angular

A service is an Angular feature used to store common data, logic, and functions.

It helps share data between multiple components.

Example:

User details like name, email, phone, address are needed on many pages such as home, profile, and settings.

Instead of writing the same data again and again, we keep it in one service.


Why Services are Important

If data changes, you update it in one place only.

Code becomes reusable.

Components stay small and clean.

Logic and UI stay separate.

API calls are always done inside services.

Without services, every component will have its own copy of data and logic, which makes the project hard to manage.


Creating a Service (Command)

ng generate service services/product

This creates:

  1. product.service.ts
  2. product.service.spec.ts

Common data, functions, and API calls are written inside the service file.


Product Service Code

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

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

constructor() {
console.log('Service Called');
}

getProducts() {
return [
{ id: 1, name: 'Mobile', price: 1000 },
{ id: 2, name: 'Laptop', price: 5000 },
{ id: 3, name: 'Machine', price: 3000 },
{ id: 4, name: 'Watch', price: 500 }
];
}
}

Constructor is used only for initialization.

It does not return data.

Data is returned using a function.


Using Service in Component (Import Style)

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

Injecting Service in Component

export class AppComponent {

productData = signal<any>([]);

constructor(private productService: ProductService) {}

@Injectable allows the service to be injected into any component.


Loading Data from Service

loadData() {
const data = this.productService.getProducts();
this.productData.set(data);
}

Service function is called using the service instance.

Returned data is stored in a variable.


HTML Code to Display Data

<h1>Products</h1>

<button (click)="loadData()">Load Data</button>

<ul>
@for (product of productData(); track product.id) {
<li>
{{ product.name }} , {{ product.price }}
</li>
}
</ul>

Data is shown only when button is clicked.

Products are displayed using loop and interpolation.