Using HTTP Interceptor Service In Angular App

HTTP Interceptor

  • A unique class of angular service that we may use is HTTP Interceptors. The core point between the client-side and server-side outgoing/incoming HTTP request and response is where custom logic is applied. Remember that just HTTP requests are what the interceptor wants.

Add HTTP Interceptor

  • The CLI command to add an interceptor service should be entered: ng generate interceptor headers

Interceptor registration

  • To utilise the HTTP interceptor in the application, we must register it. So, open the provider section of the app.module.ts file.
{
    provide: HTTP_INTERCEPTORS,
    useClass: HeadersInterceptor,
    multi: true
}

Modifying HTTP Headers By interceptor

const apiKey = 'Rohol Amin'
request = request.clone({
    setHeaders: {
        'api-key': apiKey,
    }
})
  • Serving the project is now. Click the load data button on the Network tab after opening the browser inspect window. then click the xhr type todos API. Go to the HTTP request headers after that.

Multiple interceptors

  • It is also feasible to employ several interceptors at once. All that must be done is to keep track of which service will run before and after another. In provider registration, this serialisation is described. Meaning that the provider registration serialisation will be followed by the interceptor service during execution.

{
  provide: HTTP_INTERCEPTORS,
  useClass: ResponseInterceptor,
  multi: true
}

Response Interceptor Implementation

const startTime = (new Date()).getTime();
return next.handle(request).pipe(map(event => {
    if (event instanceof HttpResponse) {
        const endTime = (new Date).getTime();
        const responseTime = endTime - startTime;
        console.log(`${event.url} succeed in ${responseTime} ms`)
    }
    return event;
}));

Output :

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories