Core Concepts

Services and Dependency Injection

Create injectable services to share logic and data across components.

What are Services?

Services are classes that contain business logic, data access, or any functionality that should be shared across multiple components.

Dependency Injection (DI)

Angular's DI system automatically provides instances of services to components that request them. You just declare what you need in the constructor — Angular does the rest.

`providedIn: 'root'`

Makes the service a singleton — the same instance is shared across the entire application.

HTTP Client

Use Angular's HttpClient to make HTTP requests. It returns Observables.

Example

typescript
// users.service.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, BehaviorSubject } from 'rxjs';
import { tap } from 'rxjs/operators';

interface User {
  id: number;
  name: string;
  email: string;
}

@Injectable({
  providedIn: 'root', // Singleton - one instance for the whole app
})
export class UsersService {
  private apiUrl = 'https://api.example.com/users';
  private usersSubject = new BehaviorSubject<User[]>([]);
  users$ = this.usersSubject.asObservable();

  constructor(private http: HttpClient) {}

  getUsers(): Observable<User[]> {
    return this.http.get<User[]>(this.apiUrl).pipe(
      tap(users => this.usersSubject.next(users))
    );
  }

  getUserById(id: number): Observable<User> {
    return this.http.get<User>(`${this.apiUrl}/${id}`);
  }

  createUser(user: Partial<User>): Observable<User> {
    return this.http.post<User>(this.apiUrl, user);
  }
}

// users-list.component.ts - inject and use service
@Component({
  template: `
    <ul>
      <li *ngFor="let user of users$ | async">{{ user.name }}</li>
    </ul>
  `
})
export class UsersListComponent implements OnInit {
  users$ = this.usersService.users$;

  constructor(private usersService: UsersService) {}

  ngOnInit() {
    this.usersService.getUsers().subscribe();
  }
}
Try it yourself — TYPESCRIPT