Services in Angular

From the Angular cheat sheet · Services & DI · verified Jul 2026

Services

Creating and using Angular services

typescript
// Service with @Injectable
@Injectable({
  providedIn: 'root'
})
export class UserService {
  constructor(private http: HttpClient) {}

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>('/api/users');
  }

  getUser(id: number): Observable<User> {
    return this.http.get<User>(\`/api/users/\${id}\`);
  }
}

// Using in component
constructor(private userService: UserService) {}

ngOnInit() {
  this.userService.getUsers().subscribe(users => {
    this.users = users;
  });
}
💡 Use providedIn: 'root' for singleton services
⚡ Handle errors gracefully with catchError
📌 BehaviorSubject for state management
🔥 Always unsubscribe to prevent memory leaks

More Angular tasks

Back to the full Angular cheat sheet