Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Request and Response Transformation

Request and response transformation allows you to modify the data being sent to and received from the server. In Angular, this can be done using HTTP interceptors to transform requests and responses efficiently.

Setting Up HTTPClientModule

First, import the HttpClientModule into your app module:

// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
import { AppComponent } from './app.component';
import { DataService } from './data.service';
import { HomeComponent } from './home/home.component';
import { TransformInterceptor } from './transform.interceptor';

@NgModule({
  declarations: [AppComponent, HomeComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    DataService,
    { provide: HTTP_INTERCEPTORS, useClass: TransformInterceptor, multi: true }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Creating an Interceptor

Create an interceptor to manage request and response transformations using the Angular CLI command:

$ ng generate interceptor transform

This command generates a new interceptor file named transform.interceptor.ts.

Implementing the Interceptor

In the interceptor file, implement the HttpInterceptor interface and define the intercept method to transform requests and responses:

// transform.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest } from '@angular/common/http';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler): Observable> {
    // Transform request
    const transformedReq = req.clone({
      setHeaders: { 'Custom-Header': 'CustomHeaderValue' }
    });

    // Transform response
    return next.handle(transformedReq).pipe(
      map(event => {
        // Modify response if needed
        return event;
      })
    );
  }
}

Using the Interceptor

HTTP interceptors are automatically applied to all HTTP requests made using the HTTPClient. You don't need to do anything special in your components to use them. Here's an example component that makes HTTP requests:

// home.component.ts
import { Component, OnInit } from '@angular/core';
import { DataService } from '../data.service';

@Component({
  selector: 'app-home',
  template: `
    

Posts

  • {{ post.title }}
` }) export class HomeComponent implements OnInit { posts: any[] = []; constructor(private dataService: DataService) {} ngOnInit() { this.dataService.getPosts().subscribe(data => { this.posts = data; }); } }

Handling Errors in Interceptors

You can also handle errors in interceptors using the catchError operator from RxJS:

// transform.interceptor.ts
import { Injectable } from '@angular/core';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError, map } from 'rxjs/operators';

@Injectable()
export class TransformInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler): Observable> {
    const transformedReq = req.clone({
      setHeaders: { 'Custom-Header': 'CustomHeaderValue' }
    });

    return next.handle(transformedReq).pipe(
      map(event => {
        return event;
      }),
      catchError((error: HttpErrorResponse) => {
        console.error('Error from interceptor', error);
        return throwError('Something went wrong');
      })
    );
  }
}

Key Points

  • Request and response transformation allows you to modify data being sent to and received from the server.
  • Import HttpClientModule in your app module to set up the HTTP Client.
  • Create an interceptor by implementing the HttpInterceptor interface.
  • Use interceptors to transform requests and responses as needed.
  • Handle errors using the catchError operator from RxJS.
  • Register interceptors in your app module using the HTTP_INTERCEPTORS token.

Conclusion

Request and response transformation is a powerful technique for managing HTTP requests and responses in Angular. By setting up interceptors, you can enhance your application's capabilities and improve its robustness. Happy coding!