How to use interceptors to modify HTTP requests and responses in Angular

0 votes
With the help of code can you explain How to use interceptors to modify HTTP requests and responses in Angular?
Mar 21 in Node-js by Nidhi
• 12,580 points
50 views

1 answer to this question.

0 votes

In Angular, interceptors are used to modify HTTP requests and responses globally. They are implemented using the HttpInterceptor interface.

Steps to Use Interceptors:

Create an Interceptor:

import { Injectable } from '@angular/core';

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

import { Observable } from 'rxjs';

@Injectable()

export class MyInterceptor implements HttpInterceptor {

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    const modifiedReq = req.clone({

      headers: req.headers.set('Authorization', 'Bearer token')

    });

    return next.handle(modifiedReq);

  }

}

Register Interceptor in AppModule:

import { HTTP_INTERCEPTORS } from '@angular/common/http';

import { MyInterceptor } from './my-interceptor';

@NgModule({

  providers: [

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

  ]

})

export class AppModule { }

answered Mar 21 by Anvi

Related Questions In Node-js

0 votes
0 answers

How to handle HTTP GET requests in Angular using HttpClient?

Can you explain with the help of ...READ MORE

Mar 19 in Node-js by Ashutosh
• 23,230 points
36 views
0 votes
1 answer

How to use switchMap to handle dependent HTTP requests in RxJS?

Using switchMap for Dependent HTTP Requests in ...READ MORE

answered 5 days ago in Node-js by anonymous
48 views
0 votes
1 answer

How to split and modify a string in NodeJS?

Hello @kartik, Use split and map function: var str = "123, 124, 234,252"; var ...READ MORE

answered Oct 16, 2020 in Node-js by Niroj
• 82,840 points
1,410 views
0 votes
1 answer

How to use middleware for logging actions and state changes in Redux?

To use middleware for logging actions and ...READ MORE

answered Mar 21 in Node-js by Anvi
58 views
0 votes
1 answer

How to unsubscribe from an observable to prevent memory leaks in Angular?

In Angular, unsubscribe from observables to prevent ...READ MORE

answered Mar 21 in Node-js by Anvi
44 views
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to cache HTTP requests in Angular

In Angular, you can cache HTTP requests ...READ MORE

answered 5 days ago in Node-js by anonymous
46 views
0 votes
1 answer

How to use the call effect in redux-saga for API requests?

To write an action creator that handles ...READ MORE

answered Mar 19 in Node-js by Tanvi
52 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP