📘
Angular Service with DI 🔧
Advanced
170 XP
70 min
Lesson Content
Angular Service with DI 🔧
Build an Angular service with dependency injection. This is core Angular architecture!
Angular Service
import { Injectable } from '@angular/core';
import { Observable, of } from 'rxjs';
interface User {
id: number;
name: string;
email: string;
}
@Injectable({
providedIn: 'root'
})
export class UserService {
private users: User[] = [];
getUsers(): Observable {
return of(this.users);
}
addUser(user: User): void {
this.users.push(user);
}
} Example Code
Create typed Angular service
interface User {
id: number;
name: string;
email: string;
}
class UserService {
private users: User[] = [];
getUsers(): User[] {
return this.users;
}
addUser(user: User): void {
this.users.push(user);
}
getUserById(id: number): User | undefined {
return this.users.find(u => u.id === id);
}
}
const service = new UserService();
service.addUser({ id: 1, name: 'John', email: 'john@example.com' });
console.log('Users:', service.getUsers());Expected Output:
User service with typed methods
Study Tips
- •Read the theory content thoroughly before practicing
- •Review the example code to understand key concepts
- •Proceed to the Practice tab when you're ready to code