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 aJSON
object so my image is gone.
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.
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.
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.
req = req.clone({ headers: req.headers.set('Accept', 'application/json'), body: {...req.body, hello: 'world' }});
something like this?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With