</>
Skip to content
Angular lessons (26/43)

Angular — API Calls

HttpClient Setup

// app.config.ts
import { provideHttpClient } from '@angular/common/http';

export const appConfig = {
  providers: [
    provideHttpClient()
  ]
};

Basic GET Request

import { HttpClient } from '@angular/common/http';
import { inject } from '@angular/core';

@Component({ ... })
export class UsersComponent {
  private http = inject(HttpClient);
  users: any[] = [];
  
  ngOnInit() {
    this.http.get<any[]>('/api/users')
      .subscribe(users => this.users = users);
  }
}

POST Request

createUser(user: any) {
  return this.http.post('/api/users', user);
}

Observable Pattern

export class UsersComponent implements OnInit, OnDestroy {
  users$ = this.http.get<any[]>('/api/users');
  private destroy$ = new Subject<void>();
  
  constructor(private http: HttpClient) {}
  
  ngOnInit() {
    this.users$
      .pipe(takeUntil(this.destroy$))
      .subscribe(users => console.log(users));
  }
  
  ngOnDestroy() {
    this.destroy$.next();
    this.destroy$.complete();
  }
}

Error Handling

this.http.get('/api/users')
  .subscribe({
    next: data => console.log(data),
    error: err => console.error('Error:', err),
    complete: () => console.log('Done')
  });

Mini Practice

  1. Set up HttpClient
  2. Make GET requests
  3. Make POST requests
  4. Handle errors

Up Next

Continue with HTTP Client — HTTP client in depth.

Related Topics

Frequently Asked Questions about API Calls

What is API Calls in Angular?

API Calls is a fundamental concept in Angular. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn API Calls?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn API Calls.

Why is API Calls important in Angular?

API Calls is essential for Angular development. Understanding this concept will help you write better code and solve real-world problems more effectively.