Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add something to the body of request inside an Angular interceptor?

Tags:

Here I'm able to modify the header as there are multiple tutorials present regarding this feature but:

@Injectable() export class MyFirstInterceptor implements HttpInterceptor {      constructor(private currentUserService: CurrentUserService) { }      intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {         console.log(JSON.stringify(req));          const token: string = this.currentUserService.token;          if (token) {             req = req.clone({ headers: req.headers.set('Authorization', 'Bearer ' + token) });         }          if (!req.headers.has('Content-Type')) {             req = req.clone({ headers: req.headers.set('Content-Type', 'application/json') });         }          req = req.clone({ headers: req.headers.set('Accept', 'application/json') });         return next.handle(req);     } } 

But in my case there's a token which I need to add the request body instead of the request header so is there any method to modify the body.

Update: Mild Fuzz's method is working great for a simple post request but I'll like to add to query if it's a GET request and body if it allows to add a body. And most importantly it broke when I tried to send a form data. ...request.body removes the form data and transforms it to a JSONobject so my image is gone.

like image 512
Black Mamba Avatar asked Nov 05 '18 06:11

Black Mamba


People also ask

What object handles the observable that an interceptor returns?

The intercept method takes two arguments, req and next, and returns an observable of type HttpEvent. req is the request object itself and is of type HTTP Request. next is the HTTP handler, of type HTTP Handler. The handler has a handle method that returns our desired HttpEvent observable.

Can I have multiple HTTP interceptors in angular?

After providing HTTP_INTERCEPTORS we need to inform the class we are going to implement our interceptor into by using useClass. Setting multi to true, makes sure that you can have multiple interceptors in your project.

What is interceptor in HTTP request?

HTTP Interceptors is a special type of angular service that we can implement. It's used to apply custom logic to the central point between the client-side and server-side outgoing/incoming HTTP request and response. Keep in mind that the interceptor wants only HTTP requests.


1 Answers

 req = req.clone({    headers: req.headers.set('Accept', 'application/json'),   body: {...req.body, hello: 'world' }}); 

something like this?

like image 182
Mild Fuzz Avatar answered Sep 20 '22 18:09

Mild Fuzz