Dynamic Setting of Content-Type Header (Multipart/Data) Through Http Interceptor



I have been trying to upload a CSV file using an HttpInterceptor as a middleware. Everything works fine for normal requests, but I need to modify the request header to 'multipart/data' specifically for CSV uploads.

Below is the code snippet:

export class NoopInterceptorService implements HttpInterceptor {
intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

        let token = this._tokenManagerService.getToken();
        const newRequest = request.clone({
            setHeaders: {
                'Content-Type': 'application/json',
                'Authorization': `${token}`
            }

        });
              return next.handle(newRequest);
    }
}

I would appreciate any suggestions on how to achieve this.

Answer №1

Here is an example of how your Http Interceptor function should look:

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            if (!req.headers.has('Content-Type')) {
                req = req.clone({headers: req.headers.set('Content-Type', 'application/json')});
            }

            req = req.clone({headers: req.headers.set( 'Authorization': ${token}``)});
            return next.handle(req);
        }

Next, you will need to set the multipart/data header in your service function. The interceptor will check if it is already set before modifying.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the correct way to declare a variable with a generic type parameter?

Exploring the following code snippet that showcases a React component being defined with a type argument named TRow: function DataTable<TRow> ({ rows: TRow[] }) { return ( ) } Prior to this implementation, ES6 was utilized and components were c ...

Guide on how to conditionally display a button or link in a Next.js Component using TypeScript

Encountering a frustrating issue with multiple typescript errors while attempting to conditionally render the Next.js Link component or a button element. If the href prop is passed, the intention is to render the Next.js built-in Link component; otherwise, ...

Utilizing TypeDoc to Directly Reference External Library Documentation

I am working on a TypeScript project and using TypeDoc to create documentation. There is an external library in my project that already has its documentation. I want to automatically link the reader to the documentation of this external library without man ...

Tips for dynamically loading a child component and passing data from the child component to the parent component

In my current setup, I have organized the components in such a way that a component named landing-home.component loads another component called client-registration-form.component using ViewContainerRef within an <ng-template>, and this rendering occu ...

Connecting multiple TypeScript files to a single template file with Angular: A comprehensive guide

Imagine you are working with a typescript file similar to the one below: @Component({ selector: 'app-product-alerts', templateUrl: './product-alerts.component.html', styleUrls: ['./product-alerts.component.css'] }) expo ...

Can you explain the purpose and functionality of the following code in Typescript: `export type Replace<T, R> = Omit<T, keyof R> & R;`

Despite my efforts, I am still struggling to grasp the concept of the Replace type. I have thoroughly reviewed the typescript documentation and gained some insight into what is happening in that line, but it remains elusive to me. ...

Testing Angular combineLatest with Jest

I'm encountering a challenge in an assessment involving a complex Statement related to combineLatest. Here is the snippet of code: component: export class ErinnerungenErinnerungenComponent implements OnInit, OnDestroy { ... erinnerungen: Erinne ...

Keeping the view up to date with changes in an Array in Angular

After extensive research through various posts and Google searches, I have yet to find a solution to this particular issue. I have explored the following two links without success: Angular doesn't update view when array was changed Updating HTML vi ...

Tips for guaranteeing the shortest possible period of operation

I am in the process of constructing a dynamic Angular Material mat-tree using data that is generated dynamically (similar to the example provided here). Once a user expands a node, a progress bar appears while the list of child nodes is fetched from the ...

What is the process for retrieving the chosen country code using material-ui-phone-number?

When incorporating user input for phone numbers, I have opted to utilize a package titled material-ui-phone-number. However, the challenge arises when attempting to retrieve the country code to verify if the user has included a 0 after the code. This infor ...

Displaying the ngx-bootstrap popover in a different position

Trying to change the position of my popover to a different location. Is it possible to position the popover differently using ng-template? <ng-template #popmeover> <button type="button" (click)='pop.hide()' class="close" aria-lab ...

Connecting RxJS Observables with HTTP requests in Angular 2 using TypeScript

Currently on the journey of teaching myself Angular2 and TypeScript after enjoying 4 years of working with AngularJS 1.*. It's been challenging, but I know that breakthrough moment is just around the corner. In my practice app, I've created a ser ...

typescript - specifying the default value for a new class instance

Is there a way to set default values for properties in TypeScript? For example, let's say we have the following class: class Person { name: string age: number constructor(name, age){ this.name = name this.age = age } } We want to ens ...

Tips for Managing Disconnection Issues in Angular 7

My goal is to display the ConnectionLost Component if the network is unavailable and the user attempts to navigate to the next page. However, if there is no network and the user does not take any action (doesn't navigate to the next page), then the c ...

Extending a Typescript class from another file

I have a total of three classes spread across three separate .ts files - ClassA, ClassB, and ClassC. Firstly, in the initial file (file a.ts), I have: //file a.ts class ClassA { } The second file contains: //file b.ts export class ClassB extends Class ...

The request to http://localhost:8000/api could not be completed due to a connection refusal error (

In the process of creating an Angular project aimed at displaying, adding, deleting, and updating employee details, I encountered persistent errors. Despite having my own API established with connections to Angular, Express, Node, and MongoDB, I continue f ...

Encountered an issue while loading the discovery document for the integration of AD FS using angular-oauth2-oid

I'm currently developing an angular SPA that requires authentication using AD FS, with Spring Boot as the backend. this.oauthService.configure({ redirectUri: window.location.origin + '/app/search', requireHttps: true, scope ...

Ensuring the validation of JSON schemas with dynamically generated keys using Typescript

I have a directory called 'schemas' that holds various JSON files containing different schemas. For instance, /schemas/banana-schema.json { "$schema": "http://json-schema.org/draft-06/schema", "type": "object", "properties": { "banan ...

Deactivating PrimeNG checkbox

I am currently facing an issue with disabling a PrimeNG checkbox under certain conditions by setting the disabled property to true. However, whenever I click on the disabled checkbox, it refreshes the page and redirects me to the rootpage /#. To troublesh ...

Oops! An error occurred: Uncaught promise rejection - invalid link found for ProductListComponent

I am currently in the process of learning Angular and Ionic, but I am feeling a bit confused as to where my mistake is. I have looked at other questions, but I still can't seem to figure it out. Can anyone provide some assistance? Perhaps someone has ...