Generics let you write flexible Angular services that work with different data types without repeating code.
0
0
Generics in Angular services
Introduction
When you want one service to handle multiple data types, like users and products.
When you want to keep your code clean and avoid copying similar service logic.
When you want type safety while reusing the same service methods.
When you build reusable data-fetching or data-processing services.
When you want to create a service that adapts to different models easily.
Syntax
Angular
export class DataService<T> { private data: T[] = []; add(item: T): void { this.data.push(item); } getAll(): T[] { return this.data; } }
The <T> after the class name means this service uses a generic type called T.
You can replace T with any type when you use the service, like DataService<User>.
Examples
This service fetches an array of any type
T from an API.Angular
import { Observable } from 'rxjs'; export class ApiService<T> { fetchAll(): Observable<T[]> { // fetch data logic return new Observable<T[]>(); } }
This service stores and retrieves items of any type
T.Angular
export class StorageService<T> { private items: T[] = []; save(item: T): void { this.items.push(item); } getItems(): T[] { return this.items; } }
Sample Program
This Angular service uses generics to store and retrieve different types of data. We create one service instance for users and another for products. Each stores its own type safely.
Angular
import { Injectable } from '@angular/core'; interface User { id: number; name: string; } interface Product { id: number; title: string; } @Injectable({ providedIn: 'root' }) export class GenericService<T> { private items: T[] = []; add(item: T): void { this.items.push(item); } getAll(): T[] { return this.items; } } // Usage example const userService = new GenericService<User>(); userService.add({ id: 1, name: 'Alice' }); userService.add({ id: 2, name: 'Bob' }); const productService = new GenericService<Product>(); productService.add({ id: 101, title: 'Book' }); console.log(userService.getAll()); console.log(productService.getAll());
OutputSuccess
Important Notes
Remember to specify the type when creating the service instance, like new GenericService<User>().
Generics help catch type errors early, making your code safer and easier to maintain.
Summary
Generics let Angular services work with any data type without rewriting code.
Use <T> to define a generic type placeholder in your service.
Specify the actual type when you create the service to get type safety and flexibility.