0
0
Angularframework~30 mins

Generics in Angular services - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Generics in Angular Services
📖 Scenario: You are building an Angular app that fetches different types of data from a server. To avoid repeating code, you want to create a generic service that can handle fetching any type of data.
🎯 Goal: Create a generic Angular service that fetches data of any type using HttpClient. Then use this service to fetch a list of users.
📋 What You'll Learn
Create a generic Angular service class called DataService with a type parameter T.
Add a method getAll() that returns an Observable of type T[].
Use Angular's HttpClient to fetch data from a URL.
Create a component that uses DataService<User> to fetch and display users.
💡 Why This Matters
🌍 Real World
Generic services reduce code duplication when fetching different data types from APIs in Angular applications.
💼 Career
Understanding generics in Angular services is important for building scalable, maintainable frontend applications in professional development.
Progress0 / 4 steps
1
Create User interface and users URL
Create an interface called User with properties id (number) and name (string). Also create a constant string variable called usersUrl with value '/api/users'.
Angular
Need a hint?

Use export interface User { id: number; name: string; } and export const usersUrl = '/api/users';

2
Create generic DataService class with HttpClient injection
Create an Angular injectable service class called DataService with a generic type parameter T. Inject HttpClient in the constructor and store it in a private variable called http. Also add a public string property called url.
Angular
Need a hint?

Use @Injectable({ providedIn: 'root' }) and inject HttpClient in constructor.

3
Add getAll() method to fetch data as Observable
Inside the DataService class, add a method called getAll() that returns this.http.get<T[]>(this.url).
Angular
Need a hint?

Use getAll(): Observable<T[]> { return this.http.get<T[]>(this.url); }

4
Use DataService<User> in a component to fetch users
Create an Angular component class called UserListComponent. Inject DataService<User> in the constructor as userService. Set userService.url = usersUrl in the constructor. Add a public property users of type User[] initialized as an empty array. In ngOnInit(), subscribe to userService.getAll() and assign the result to this.users.
Angular
Need a hint?

Use @Component with selector and template. Inject DataService<User> and set url. Subscribe in ngOnInit().