Angular 6 is experiencing a failure to send the Authorization Header

I have set up an HttpInterceptor to include an Authorization Header Token and I am attempting to handle http errors. However, the Authorization header is not being sent. Everything was working correctly before I added the error handler. I have also made sure to register my interceptor in the AppModule.

// Here is my interceptor.ts code snippet

import {Injectable} from '@angular/core';
import {HttpEvent, HttpInterceptor, HttpHandler,
    HttpRequest, HttpErrorResponse} from '@angular/common/http';
import {Observable, of} from 'rxjs';
import {catchError} from "rxjs/internal/operators";
import {ToastrService} from "ngx-toastr";

@Injectable()
export class MyInterceptor implements HttpInterceptor {

    constructor(private toastService: ToastrService)
    {

    }
    intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        let reqHeader;
        if(sessionStorage.getItem('token') !== null || sessionStorage.getItem('token') !== undefined)
            reqHeader = req.clone({headers: req.headers.set('Authorization',
            sessionStorage.getItem('token'))});
        else
            reqHeader = req.clone({headers: req.headers.set('Authorization', "123")});


        return next.handle(req).pipe(catchError((error, caught) => {
            console.log(error);
            this.handleAuthError(error);
            return of(error);
        }) as any);

    }


    /**
    * manage errors
    * @param err
    * @returns {any}
    */
    private handleAuthError(err: HttpErrorResponse): Observable<any> {
        //handle your auth error or rethrow

        console.log(err);
        this.toastService.error("Error Received","Err");
        throw err;
    }

}

// Here is my App Module.ts code snippet

providers: [{
provide: HTTP_INTERCEPTORS,
useClass: MyInterceptor,
multi: true,
}

Answer №1

After reviewing your code, I noticed that you were not handling errors correctly. Please see the updated code below.

    import { Injectable } from '@angular/core';
    import { HttpInterceptor, HttpEvent, HttpHandler, HttpRequest, HttpErrorResponse } from '@angular/common/http';
    import { Observable, throwError } from 'rxjs';
    import { catchError } from 'rxjs/operators';

    @Injectable({
        providedIn: 'root'
    })
    export class IntercepterHttp implements HttpInterceptor {
        constructor(
        ) { }

        intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
            let reqHeader;
            if(sessionStorage.getItem('token')!=null || sessionStorage.getItem('token')!=undefined)
            reqHeader = req.clone({headers: req.headers.set('Authorization', 
        sessionStorage.getItem('token'))});
    else
        reqHeader = req.clone({headers: req.headers.set('Authorization', "123")});

            return next.handle(reqHeader).pipe(
                catchError(response => {
                    if (response instanceof HttpErrorResponse) {
                        return throwError(response);
                    }
                })
            )
        }
    }

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 best way to retrieve an item from an array?

I have an array containing multiple records and I need to extract just one record from it using its id as an object. However, the result I'm getting is an array with that single record. Is there a way to resolve this issue? Result: [{…}] 0: {id ...

Engage with the item provided to an Angular2 component as an Input parameter

In a nutshell, the issue stems from a missing 'this' when referencing the @Input'ed variables. Currently, I have a parent class that will eventually showcase a list of "QuestionComponents". The pertinent section of the parent class templat ...

"Utilize an Angular button to upload a locally stored JSON file and populate a data

Hey everyone, I'm looking to use a button to load a local file and convert the file data into a jsonObject. The HTML structure: <div class="uuidLableLeft"> <b>Do you want to import your previous file (.json)?</b> <input style ...

Ensuring Data Consistency: Using TypeScript to Strongly Type Arrays with Mixed Variable Types

I have a JSON array that may contain objects of two types, defined by IPerson and ICompany. [ { "Name" : "Bob", "Age" : 50, "Address": "New Jersey"}, { "Name" : "AB ...

Processing of hierarchical JSON structure

I have a JSON array that I am trying to duplicate only once while keeping it unique. Here is the code I have attempted: return_data = {}; return_data.planner = [{ "date": "2019-08-30T12:10:08.000Z", "event": [{ "name": "Event 1", "col ...

Exploring the synergy between Visual Studio 2015 and Angular2 Beta 2's dependency injection functionality

Currently, I am using VS2015 alongside TypeScript 1.7.3 and Angular2 Beta 2 with a target of ECMA 5. In order to enable experimental decorators in my project, I have made modifications to the csproj file by including TypeScriptExperimentalDecorators = true ...

Kendo's comboBox for local virtualization

Looking to implement virtualization for local data using the kendo object ComboBox. I've tried different methods, but only the current page (first 40 elements) is displayed. I followed a code structure similar to the kendo virtualization tutorial an ...

Facing a problem with running npm start on jHipster

I am currently working on a jhipster project on my MacBook Pro running macOS Mojave v.10.14.4. After successfully compiling with npm start, the code continues to compile multiple times without any changes. Eventually, it throws the following error: DONE ...

Can you specify a data type for ngFor in Angular?

I am currently employing ngFor to iterate over a collection of a specific type [Menu] within Angular 4.x. During this process, I am looping through a collection property of the menu object (menu.items). Unfortunately, my IDE (Eclipse + Angular IDE) is un ...

Place the Div in a consistent position on images of varying widths

I have a dilemma with my class that is supposed to display images. The issue arises when I try to place a div within an image inside this class. Everything works smoothly when the image takes up the entire width of the class, but as soon as the image widt ...

Determine the size of a BSON object before saving it to a MongoDB database using

I am currently in the process of determining the best way to calculate the size before storing certain data in MongoDB. After writing a script that parses and combines data into a single document, I have encountered an error when trying to use instance.sav ...

Angular EventEmitter fails to emit event

I am currently working with an Angular vertical stepper (using Angular Material) consisting of separate components for each step, with a parent component calling all these child components. My challenge is in passing data between the parent and child compo ...

Providing Access to Data Across Various Modules

I currently have an application structured like this: AppModule SubModule Multiple Components SecondSubModule Multiple Components I am looking to perform a data call to a REST API that will be used by both SubModule and SecondSubM ...

How can @ngrx be utilized to retrieve data based on the route?

Our webapp requires users to click through lists to reach a specific edit view. For example, starting from the landing page, a user selects a client, then an agent, and finally reaches the edit view of that agent. The URL in this scenario would contain the ...

Using Angular to send a text to an injection service

i have developed a generic CRUD service that utilizes HttpClient through Dependency Injection (DI). However, I need to include another value in the constructor of this service. How can I achieve this? the issue arises when attempting to define this additi ...

Limit access to a specific route within the URL

Is there a way to ensure that users can access and download myfile.pdf without being able to see or access /root, /folder, or /subdirectory in the URL? This functionality can be implemented using HTML, Angular 6, ReactJS, or similar frameworks. ...

Attempting to create a login feature using phpMyAdmin in Ionic framework

Currently, I am in the process of developing a login feature for my mobile application using Ionic. I am facing some difficulties with sending data from Ionic to PHP and I can't seem to figure out what the issue is. This is how the HTML form looks li ...

Retrieving the key from an object using an indexed signature in Typescript

I have a TypeScript module where I am importing a specific type and function: type Attributes = { [key: string]: number; }; function Fn<KeysOfAttributes extends string>(opts: { attributes: Attributes }): any { // ... } Unfortunately, I am unab ...

You are able to use a null type as an index in angular.ts(2538) error message occurred

onClick() { let obj = { fName: "ali", LName: "sarabi", age: "19", } let fieldName = prompt("field"); alert(obj[fieldName]); } I encountered an issue with the code above where alert(obj[fieldName] ...

Transferring multiple parameters between components using Navigate and ParamMap

My concern is that I'm unsure of how to pass multiple parameters through the component's route. I need to send two attributes. Is there a specific syntax required in defining the route? Below is my desired functionality for passing the attribut ...