How do you handle API calls in Angular?
Handling API calls is one of the most common tasks in Angular applications. Angular mainly uses the HttpClient service for communicating with backend APIs.
1. Which module is used for API calls in Angular?
Angular provides the HttpClientModule and HttpClient service.
Import HttpClientModule
In standalone Angular applications:
import { provideHttpClient } from '@angular/common/http';
bootstrapApplication(AppComponent, {
providers: [provideHttpClient()]
});
In older module-based applications:
import { HttpClientModule } from '@angular/common/http';
@NgModule({
imports: [HttpClientModule]
})
export class AppModule { }
2. Inject HttpClient into a Service
Best practice is to place API logic inside a service, not directly in components.
Example Service
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class UserService {
private apiUrl = 'https://api.example.com/users';
constructor(private http: HttpClient) {}
getUsers(): Observable<any> {
return this.http.get(this.apiUrl);
}
}
3. Calling API from Component
import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
@Component({
selector: 'app-users',
templateUrl: './users.component.html'
})
export class UsersComponent implements OnInit {
users: any[] = [];
constructor(private userService: UserService) {}
ngOnInit(): void {
this.loadUsers();
}
loadUsers() {
this.userService.getUsers().subscribe({
next: (response) => {
this.users = response;
},
error: (error) => {
console.error(error);
}
});
}
}
4. Common HTTP Methods
Angular supports all major HTTP operations.
| Method | Purpose |
|---|---|
| GET | Fetch data |
| POST | Create data |
| PUT | Replace existing data |
| PATCH | Partially update data |
| DELETE | Delete data |
5. Examples of HTTP Methods
GET Request
this.http.get('/api/users');
POST Request
this.http.post('/api/users', userData);
PUT Request
this.http.put('/api/users/1', updatedData);
PATCH Request
this.http.patch('/api/users/1', partialData);
DELETE Request
this.http.delete('/api/users/1');
6. Why Angular Uses Observables for API Calls
Angular’s HttpClient returns Observables from RxJS.
Advantages:
-
Asynchronous handling
-
Supports streams of data
-
Easy cancellation
-
Powerful operators
-
Better for reactive programming
7. Error Handling in API Calls
Usually handled using:
-
catchError -
HttpInterceptor -
Error callbacks in
subscribe
Example Using catchError
import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';
getUsers() {
return this.http.get(this.apiUrl).pipe(
catchError(error => {
console.error('API Error', error);
return throwError(() => error);
})
);
}
8. What are Interceptors?
Interceptors allow us to intercept all HTTP requests and responses globally.
Used for:
-
Adding JWT tokens
-
Logging
-
Error handling
-
Loading spinners
-
Request modification
9. Example of HTTP Interceptor
import { HttpInterceptorFn } from '@angular/common/http';
export const authInterceptor: HttpInterceptorFn = (req, next) => {
const modifiedReq = req.clone({
setHeaders: {
Authorization: 'Bearer token'
}
});
return next(modifiedReq);
};
Register:
provideHttpClient(withInterceptors([authInterceptor]))
10. How to Send Headers
import { HttpHeaders } from '@angular/common/http';
const headers = new HttpHeaders({
Authorization: 'Bearer token'
});
this.http.get('/api/users', { headers });
11. How to Send Query Parameters
import { HttpParams } from '@angular/common/http';
const params = new HttpParams()
.set('page', '1')
.set('size', '10');
this.http.get('/api/users', { params });
12. Async Pipe vs Subscribe
Using Subscribe
this.userService.getUsers().subscribe(data => {
this.users = data;
});
Using Async Pipe
users$ = this.userService.getUsers();
<div *ngFor="let user of users$ | async">
{{ user.name }}
</div>
Why Async Pipe is Better
-
Automatically unsubscribes
-
Cleaner code
-
Prevents memory leaks
13. How to Avoid Memory Leaks
When manually subscribing, unsubscribe properly.
Old Approach
subscription!: Subscription;
ngOnInit() {
this.subscription = this.userService.getUsers()
.subscribe();
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
Modern Angular Approach
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
this.userService.getUsers()
.pipe(takeUntilDestroyed())
.subscribe();
14. Best Practices for API Calls
Use Services
Keep components clean.
Use Strong Typing
interface User {
id: number;
name: string;
}
getUsers(): Observable<User[]> {
return this.http.get<User[]>(this.apiUrl);
}
Centralize API URLs
Use environment files.
export const environment = {
apiUrl: 'https://api.example.com'
};
Use Interceptors
Avoid repeating auth logic everywhere.
Handle Errors Gracefully
Show proper messages to users.
Avoid Nested Subscriptions
Use RxJS operators like:
-
switchMap -
mergeMap -
forkJoin -
combineLatest
15. Frequently Asked Interview Questions
Q1. Why use services for API calls instead of components?
Because services:
-
Improve reusability
-
Follow separation of concerns
-
Keep components clean
-
Simplify testing
Q2. Why does HttpClient return Observables instead of Promises?
Observables:
-
Support multiple values
-
Can be cancelled
-
Have RxJS operators
-
Better for reactive applications
Q3. What is the difference between Promise and Observable?
| Promise | Observable |
|---|---|
| Single value | Multiple values |
| Cannot cancel | Can cancel |
| Limited operators | Rich RxJS operators |
| Executes immediately | Lazy execution |
Q4. What are Interceptors in Angular?
Interceptors are middleware-like functions that intercept HTTP requests/responses globally.
Q5. Which RxJS operators are commonly used with API calls?
Common operators:
-
map -
switchMap -
mergeMap -
debounceTime -
catchError -
retry -
forkJoin
16. Real-Time Interview Tip
In interviews, explain API handling in this order:
-
HttpClientModule
-
Service layer
-
Observables
-
Subscribe/async pipe
-
Error handling
-
Interceptors
-
RxJS operators
-
Memory leak prevention
-
Best practices
That gives a complete professional answer.
