Interceptors in Angular 8 TypeScript prevent setting Headers until the token is stored in local storage

Whenever I attempt to log in, the interceptors fail to set the header of the request because it runs before the .pipe() block of service. As a result, currentUser in interceptors is always null. ///////////////////////////////////////////////////////////////

http-interceptor.service.ts

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

    let currentUser = this.logInService.currentUserVal;
    if (currentUser) {
      req = this.addToken(req, currentUser);
    }
    return next.handle(req).pipe(catchError(this.handleError));
  } 

login.service.ts

  public _currentUserSubject: BehaviorSubject<AuthRequest>;
  public currentUser: Observable<AuthRequest>;

  public get currentUserVal(): AuthRequest {
    return this._currentUserSubject.value;
  }

  get currentUserToken() {
    return this.currentUserVal;
  }

  constructor(private httpClient: HttpClient) {

    this._currentUserSubject = new BehaviorSubject<AuthRequest>(this.getUserFromLocalStorage());
    this.currentUser = this._currentUserSubject.asObservable();

  }

  generateToken(authRequest: AuthRequest) {
    return this.httpClient.post<any>(`${this.glolabUrl}${this.authetnticationUrl}`, authRequest, { responseType: 'text' as 'json' })
      .pipe( map(user => {
          localStorage.setItem(this.JWT_TOKEN, JSON.stringify(user));
          this._currentUserSubject.next(user);
          return user;
        })
      );
  }

login.component.ts

    toAuthenticate() {
    this.submitted = true;
    if (this.loginForm.invalid) {
      return;
    }
    this.spinner.show();
    this.authSubscription = this.logInService.generateToken(this.authRequest)
    // .pipe(first())
    .subscribe(
      data => {
        this.logInService.autoritySubject.next(true);
        this.router.navigate(['home']);
        setTimeout(() => {
          this.spinner.hide();
        }, 500);
      },

      err => {
        console.log(err);
        this.spinner.show();
        this.failedMessage = err;
        this.failed = true;
        this.onReset();
        setTimeout(() => {
          this.spinner.hide();
        }, 500);
      }
    );
  }

Answer №1

To intercept and modify your HTTP request in an HttpInterceptor, you should implement something similar to the following code snippet:

  let currentUser = this.userService.getCurrentUser();
    if (currentUser) {
       req = req.clone({
        headers: req.headers.set('Authorization', `Bearer ${currentUser.token}`)
    }
    
    return next.handle(req).pipe(
         retry(1),
         catchError((error: HttpErrorResponse) => {
            if (error.status === 401) {
               // Handle token refresh logic here
               console.log('Token expired, refreshing...');
            } else {
               return throwError(error);
            }
         })
     );

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

Updating CSS class for a label when a radio button is selected in Angular 6

Within my Angular component, I've set up a radio button group like so: <label class="btn-{{cl1}}"> <input type="radio" value="am" name="time" formControlName="time1" (change)="cl1=active" >9:00am </label> I am looking for an effi ...

The correct way to subscribe to an Observable within Angular:

My goal is to create a valid observable by making a GET request and subscribing to it. This way, I can utilize the retrieved data in multiple components within my application. The expected JSON structure from the server should look similar to this: { " ...

An issue has arisen where Selenium Auth0 is unable to establish a connection with the server

I am using a protractor selenium test for an angular2 application that I execute with the command protractor conf.js --params.login.username=John --params.login.password=Doe. The purpose of the test is to attempt to log in to the backend and intentionally ...

Guide on incorporating Kendo UI typings into a TypeScript module

Currently, I am working with Kendo UI for React and TypeScript. My goal is to import the Kendo UI typings for TypeScript using a "typeof import". Following the guidance provided at https://docs.telerik.com/kendo-ui/third-party/typescript, I successfully i ...

Each time a click is made, an Uncaught TypeError occurs, indicating that it is unable to read properties from an undefined source (specifically

I have successfully built my React website but I am encountering a console error that I am trying to resolve. Each click on the page triggers the following error: Uncaught TypeError: Cannot read properties of undefined (reading '0') at Array. ...

The JSX component is unable to utilize the object

When working with Typescript in a react-three-fiber scene, I encountered an error that GroundLoadTextures cannot be used as a JSX component. My aim is to create a texture loader component that loads textures for use in other components. The issue arises f ...

Monitoring changes in the Firebase database using TypeScript

Currently, I am accessing my firebase realtime database through an angular service with the following code: readItems() { return this.af.database.ref(`/path`) .on('value', snap => this.callback(snap.val())); } The callback functi ...

Dealing with checkbox changes in Angular 2

I have a checkbox that is initially checked, and I want to use the (change) event on it. After being clicked, I want to clear the input text for "Activation key". When re-checked, I want to generate a GUID and add it back to the input field. How can I dete ...

Unable to interact with Span in a table cell - Protractor/Typescript error

I am facing an issue where clicking on the Span Element within a Grid cell is not working. I have tried using actions and the code below, but neither worked for me. Any advice would be greatly appreciated. async SaveorCancelRow() { var table = this. ...

Encountered an error while running the ag-grid ng build command in production mode: "Maximum call

Problem: When running ng build, I encounter a failure related to ag-grid gridOptionsWrapper. The error message is shown below. Error Message: Module build failed: RangeError: Maximum call stack size exceeded at Object.forEachChild ... (Full error ...

Retrieve a list of class names associated with a Playwright element

Can anyone suggest the best method to retrieve an array of all class names for an element in Playwright using TypeScript? I've searched for an API but couldn't find one, so I ended up creating the following solution: export const getClassNames = ...

Guide to implementing a dropdown menu for selecting countries in Angular

Recently, I was involved in an ecommerce project that required a login feature with a country code selection option for mobile users. I'm currently using Angular 7 for this project and was wondering if there are any packages available that can provide ...

The declaration merging for react-table types is not functioning properly as the property does not exist on the type 'TableInstance'

While working on implementing pagination for my react-table component, I encountered a strange issue. The error message "Property X does not exist on type 'TableInstance'" is visible in the screenshot below: https://i.sstatic.net/1WpAf.png To a ...

The resizing of containers will not affect the charts

Currently, I have integrated an ng2 Line Chart into a custom container to resemble a mat-card. However, when the navigation panel is hidden and the entire page is displayed, the container resizes but the charts do not. They only resize if placed on their o ...

Connecting Angular forms to retrieve form data using email

Hello, I am new to Angular and haven't had experience hosting a website before. I have created a contact form on my website and would like the form inputs to be sent to my email address whenever someone submits the form. Can anyone guide me on how to ...

The request to search for "aq" on localhost at port 8100 using Ionic 2 resulted in a 404 error, indicating that the

Trying to create a basic app that utilizes an http request, but facing challenges with cors in ionic 2. To begin with, modifications were made to the ionic.config.json { "name": "weatherapp", "app_id": "", "v2": true, "typescript": true, "prox ...

One press sets off a chain reaction of unintended consequences

I am facing an issue where I want to implement functionality to modify the quantity of a selected product using two buttons: minus and plus. Strangely, when clicking the plus button it also triggers the click event of the minus button. Can anyone shed li ...

Update not reflected in parent form when using ValueChanges in Angular's ControlValueAccessor

Here is the code snippet I am currently working with: https://stackblitz.com/edit/angular-control-value-accessor-form-submitted-val-egkreh?file=src/app/app.component.html I have set default values for the form fields, but when clicking the button, the pa ...

To modify the pageSize of the KendoGrid in order to display 1-10 out of 100, you can customize the appearance and functionality of the page numbers by changing

I am currently working on a kendo grid that utilizes the traditional [kendoGridBinding]="gridData" method as shown below - `<kendo-grid #grid [kendoGridBinding]="gridData" [pageable]="true" [pageSize]="5" style="cursor:pointer"> <kendo-grid ...

Angular form with dynamically generated nested inputs

I am attempting to extract the values from the input fields within this dynamically generated form. Each time the user clicks the button, new input fields are added. However, I am unsure of the correct method to retrieve this data based on the documentatio ...