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

Viewed 16621

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.

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

something like this?

Thanks to Mild Fuzz that was what I wanted but in my case I had some complications which I was able to solve with some extra headache. Here's my final implementation:

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

    console.log('Intercepted!', req);
    const authService = this.injector.get(AuthService);
    const reqCloned =  this.handleBodyIn(req, localStorage.getItem('random_key'), 'random_key_added');
    const copiedReq = reqCloned;
    return next.handle(copiedReq);
  }
  handleBodyIn(req:HttpRequest<any>, tokenToAdd, tokenName) {
    if (req.method.toLowerCase() === 'post') {
      if (req.body instanceof FormData) {
        req =  req.clone({
          body: req.body.append(tokenName, tokenToAdd)
        })
      } else {
        const foo = {}; foo[tokenName] = tokenToAdd;
        req =  req.clone({
          body: {...req.body, ...foo}
        })
      }            
    } 
    if (req.method.toLowerCase() === 'get') {
      req = req.clone({
        params: req.params.set(tokenName, tokenName)
      });
    } 
    return req;    
  }
}

Here's the editor link if any one else wants to check.

Here's a working example:

intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        const clonedreq = req.clone({
            headers: req.headers.set("Authorization", "Bearer " + sessionStorage.getItem('userToken'))
        });
        return next.handle(clonedreq)
            .do(
            succ => {
                if(succ["status"] != null && succ["status"] != undefined){
                    this.loaderService.handleResponse('regular');
                }
             },
            err => {
                if (err.status === 401)
                    this.router.navigateByUrl('/Login');
                this.loaderService.handleResponse('regular');
            }
        );
}
Related