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

Using TypeScript to utilize an enum that has been declared in a separate file

Imagine I have defined an enum in one file (test1.ts): export enum Colors{ red=1, blue=2, green=3 } Then in another file (test2.ts), I am creating a class with a method. One of the parameters for that method is a Color from the Colors enum: ...

Display the concealed mat-option once all other options have been filtered out

My current task involves dynamically creating multiple <mat-select> elements based on the number of "tag types" retrieved from the backend. These <mat-select> elements are then filled with tag data. Users have the ability to add new "tag types, ...

Enhance your coding experience with code completion and autocomplete in Angular/Typescript using ATOM within

Is it possible to have Codecompletion / Autocomplete in Atom similar to Webstorm? Currently I am getting familiar with TypeScript and really enjoying it, but the lack of Codecompletion support for my HTML files in Atom is quite frustrating. Having this f ...

Is there a way to optimize Typescript compiler to avoid checking full classes and improve performance?

After experiencing slow Typescript compilation times, I decided to utilize generateTrace from https://github.com/microsoft/TypeScript/pull/40063 The trace revealed that a significant amount of time was spent comparing intricate classes with their subclass ...

There was an error encountered: Uncaught TypeError - Unable to access the 'append' property of null in a Typescript script

I encountered the following error: Uncaught TypeError: Cannot read property 'append' of null in typescript export class UserForm { constructor(public parent: Element) {} template(): string { return ` <div> < ...

Changes made to the updated component fields are not reflecting on the user interface

I've encountered an issue where I can't seem to update a variable in a component that is being displayed on the UI. Even though the content of the variable changes correctly, the UI fails to reflect this change. Strangely enough, when checking th ...

Using Angular 2 to assign a function to the ngClass directive within the template

I've been searching for a solution to this issue, but so far nothing has worked for me. When I try to pass a function to the ngStyle directive, I encounter the following error: The expression 'getClass()' in ProductView has changed after i ...

Altering the appearance of an Angular component in real-time by applying various CSS style sheets

I'm currently working on implementing a dynamic style-sheet change for a single-page application using Angular. The concept is to offer users the ability to select from various themes through a dedicated menu. Although only two theme variants are show ...

Utilize an exported class as a type within a .d.ts file

I have two classes, ./class1.ts and ./class2.ts, with the following structure: export class Class1{ ... } and export class Class2{ ... } In my file ./run.ts, there is a function that accepts a class input function doSomething(klass: ClassType){ l ...

In TypeScript, the first element of an array can be inferred based on the second element

Let's consider a scenario where we have a variable arr, which can be of type [number, 'number'] or [null, 'null']. Can we determine the type of arr[0] based on the value of arr[1]? The challenge here is that traditional function ov ...

The Vue Prop does not have an initializer and is not explicitly assigned in the constructor

Currently, I am utilizing props in Vue Class components. Within the constructor, I have defined the props without a value. This setup compiles and operates smoothly, except after the most recent VS Code / TSLint update, a warning message emerges: The pr ...

What could be causing the module to break when my Angular service, which includes the httpClient, is added in the constructor?

After creating a backend RESTful API, I encountered difficulties while trying to access it. To address this issue, I developed a database-connection.service specifically for making POST requests. However, I am facing challenges in implementing this solut ...

The selected check icon does not appear in the console log

Objective: Display preselected data from selected checkbox in console.log Issue: The preselected data is not appearing in the console log. When manually checked, the data shows up. What am I missing? About Me: I am a beginner in Angular. Thank ...

Designing Angular2 Routing - Comparing Default Navigation Components to Login Implementation

I'm seeking guidance on the best approach in Angular2 for displaying a different view depending on whether the user is logged in or not. When a user is logged in, I want to display a navigation and menu bar component by default outside of the router- ...

Creating a gradient background with the makeStyles function

Why is it that the background: 'linear-gradient(to right, blue.200, blue.700)' doesn't work within makeStyles? I just want to add a gradient background to the entire area. Do you think <Container className={classes.root}> should be rep ...

A guide on utilizing the useEffect hook to dynamically update a button icon when hovering over it in a React application

Is it possible to change the icon on a button when hovering using useEffect? <Button style={{ backgroundColor: "transparent" }} type="primary" icon={<img src={plusCart} />} onCl ...

Converting Getters into JSON

I am working with a sequelize model named User that has a getter field: public get isExternalUser(): boolean { return this.externalLogins.length > 0; } After fetching the User from the database, I noticed in the debugger that the isExternalUser prop ...

Ensure that TypeScript compiled files are set to read-only mode

There is a suggestion on GitHub to implement a feature in tsc that would mark compiled files as readonly. However, it has been deemed not feasible and will not be pursued. As someone who tends to accidentally modify compiled files instead of the source fil ...

Value is not defined when subscribing to subject in Event Bus Implementation

After creating an EventBusService and EventData, here is the implementation: export class EventData { public eventName: string; public event: any; constructor(eventName: string, event: any) { this.eventName = eventName; this.e ...

Testing the Compatibility of Angular JS and Angular 8 in a Hybrid Application

I am currently working on a hybrid application using AngularJS and Angular 8. The new components I create in Angular need to be downgraded for use in AngularJS. Here is a snippet of the module code: @NgModule({ // Declarations and Imports providers ...