HTTP & API Integration in Angular - Textnotes

HTTP & API Integration in Angular


Angular provides the HttpClientModule to communicate with backend APIs. You can perform HTTP requests, handle responses, manage errors, and implement authentication using JWT.

1. HttpClientModule

First, import HttpClientModule in your AppModule:


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule } from '@angular/common/http';

@NgModule({
imports: [
BrowserModule,
HttpClientModule
]
})
export class AppModule { }

Inject HttpClient in your service to make API calls:


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

@Injectable({
providedIn: 'root'
})
export class ApiService {
constructor(private http: HttpClient) { }
}

2. GET, POST, PUT, DELETE Calls

GET Request


getUsers() {
return this.http.get('https://api.example.com/users');
}

POST Request


addUser(user: any) {
return this.http.post('https://api.example.com/users', user);
}

PUT Request


updateUser(id: number, user: any) {
return this.http.put(`https://api.example.com/users/${id}`, user);
}

DELETE Request


deleteUser(id: number) {
return this.http.delete(`https://api.example.com/users/${id}`);
}

3. Observables & RxJS

All HttpClient methods return Observables. Subscribe to get data:


this.apiService.getUsers().subscribe({
next: (data) => console.log(data),
error: (err) => console.error(err)
});

You can also use RxJS operators like map, catchError, tap:


import { catchError, map } from 'rxjs/operators';
import { of } from 'rxjs';

this.apiService.getUsers().pipe(
map(res => res),
catchError(err => of([]))
).subscribe(data => console.log(data));

4. Handling Responses

Use subscribe to handle responses and errors:


this.apiService.getUsers().subscribe({
next: (res) => this.users = res,
error: (err) => this.errorMessage = err.message
});

5. HTTP Interceptors

Interceptors allow you to modify HTTP requests or responses.

Example: Adding a token


import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';
import { Injectable } from '@angular/core';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler) {
const token = localStorage.getItem('token');
const clonedReq = req.clone({
headers: req.headers.set('Authorization', `Bearer ${token}`)
});
return next.handle(clonedReq);
}
}

Register the interceptor:


providers: [
{ provide: HTTP_INTERCEPTORS, useClass: AuthInterceptor, multi: true }
]

Interceptors can also be used for logging or error handling globally.

6. Error Handling

Catch errors in services using RxJS:


import { catchError } from 'rxjs/operators';
import { throwError } from 'rxjs';

getUsers() {
return this.http.get('https://api.example.com/users').pipe(
catchError(error => {
console.error('Error occurred:', error);
return throwError(error);
})
);
}

7. JWT Authentication Flow

  1. Login: Send username/password to backend. Receive JWT token.
  2. Store Token: Save JWT in localStorage or sessionStorage.
  3. Attach Token: Use HTTP interceptor to attach token in request headers.
  4. Protect Routes: Backend validates JWT for secure endpoints.
  5. Logout: Remove token from storage.

Example of storing token:


localStorage.setItem('token', res.token);

Attach in interceptor as shown above.

Summary

  1. Import HttpClientModule to use HttpClient
  2. Perform API calls: GET, POST, PUT, DELETE
  3. Responses are Observables, handled using subscribe and RxJS operators
  4. Use HTTP interceptors for tokens, logging, or error handling
  5. Handle errors using catchError
  6. Implement JWT authentication flow for secure API communication