How to chage content-type in interceptor in angular 6?

Viewed 6808

Some services need to have token,some have different Content-Type.how should I manage them in an Interceptor file?

1 Answers

You can get or set all request headers on your interceptor function. The following code reveals headers proprty for handling this changes:

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

    if (request.headers.has('Content-Type'))
       contentType = request.headers.get('Content-Type');

    request = request.clone({
      setHeaders: {
        'Authorization': `Bearer ${this.auth.getToken()}`,
        'Content-Type': (contentType != 'application/json' ? 'application/text' :  contentType)
      }
    });
    return next.handle(request);
  }
Related