Working with APIs in Angular
Working with APIs in Angular
Angular HTTP Client
Angular provides the HttpClient service to communicate with REST APIs. It supports operations such as GET, POST, PUT, PATCH, and DELETE while automatically converting JSON responses into JavaScript objects.
First, enable the HTTP Client.
// app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';
import { provideHttpClient } from '@angular/common/http';
import { routes } from './app.routes';
export const appConfig: ApplicationConfig = {
providers: [
provideRouter(routes),
provideHttpClient()
]
};
Generate a reusable service.
ng generate service course
Angular creates two files inside the **src/app** folder:
course.ts
course.spec.ts
Open **course.ts** and update it as shown below.
// course.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class Course {
apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) {}
getCourses() {
return this.http.get<any[]>(this.apiUrl);
}
}
Instead of placing API logic inside components, Angular recommends using services. This keeps components clean and allows multiple components to reuse the same business logic.
GET and POST Requests
A GET request retrieves information from the server, while a POST request sends new information to the server.
Update course.ts.
// course.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Injectable({
providedIn: 'root'
})
export class Course {
apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) {}
getCourses() {
return this.http.get<any[]>(this.apiUrl);
}
addCourse(course: any) {
return this.http.post(this.apiUrl, course);
}
}
Retrieve the API data inside the Courses component.
// courses.ts
import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterLink } from '@angular/router';
import { Course } from '../course';
@Component({
selector: 'app-courses',
standalone: true,
imports: [CommonModule, RouterLink],
templateUrl: './courses.html',
styleUrl: './courses.css'
})
export class Courses implements OnInit {
courses: any[] = [];
constructor(private courseService: Course) {}
ngOnInit(): void {
this.courseService.getCourses().subscribe(data => {
this.courses = data.slice(0, 10);
});
}
}
Display the retrieved data.
<!-- courses.html -->
<h2>Courses</h2>
<ul>
<li *ngFor="let course of courses">
{{ course.title }}
</li>
</ul>
Error Handling
Network requests can fail due to connectivity problems, unavailable servers, or invalid endpoints. Angular provides the catchError operator to handle these situations gracefully.
Update course.ts.
// course.ts
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class Course {
apiUrl = 'https://jsonplaceholder.typicode.com/posts';
constructor(private http: HttpClient) {}
getCourses() {
return this.http.get<any[]>(this.apiUrl).pipe(
catchError(error => {
console.error('API Error:', error);
return throwError(() => error);
})
);
}
addCourse(course: any) {
return this.http.post(this.apiUrl, course);
}
}
With proper error handling, the application continues running even if an API request fails. Instead of crashing, Angular can display an appropriate error message or retry the request.











