Troubleshooting Angular 5: Interceptor Fails to Intercept Requests

I have a valid JWT token stored in local storage and an interceptor that I borrowed from a tutorial. However, the interceptor is not intercepting requests and adding headers as expected.

Here's where I am making a request:

https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/services/information.service.ts

Here is the code for the interceptor:

https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/services/token.interceptor.ts

In addition, I believe my appmodule is correctly imported:

https://github.com/Marred/Informakcja/blob/master/Informakcja-client/src/app/app.module.ts

When I make a request, I expect the interceptor to log specific messages to the console and add the token to the header. However, it is not functioning as intended and I am unsure why. I compared my code to other online tutorials but did not find any differences that could be causing this issue. My experience with Angular is limited, so debugging this has been challenging.

Any assistance or guidance would be greatly appreciated.

Answer №1

There are a couple of things that need to be corrected in your implementation:

Interceptors should be used with HttpClientModule instead of HttpModule. Currently, you are using HttpModule which needs to be changed to HttpClientModule.

  1. Add HttpClientModule to the imports array in your app.module.ts
  2. Import HttpClient in your authentication.service.ts file and include its reference in the constructor.

Refer to the following code snippets for guidance:

// app.module.ts
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';
.
.
@NgModule({
  imports: [
    BrowserModule,
    HttpClientModule, // add here
    RouterModule.forRoot([
      // routes configuration
    ]),
  ],
  providers: [
    // other service providers
    {
      provide: HTTP_INTERCEPTORS,
      useClass: TokenInterceptor,
      multi: true
    }
  ]
})
export class AppModule { }

and

// information.service.ts and authentication.service.ts

import { HttpClient} from '@angular/common/http'; // add import statement
.
.
@Injectable()
export class InformationService {

  constructor(private http: HttpClient) { } // make changes in constructor

  add(link: string, title: string, description: string) {
    return this.http.post('api/Information', { link: link, title: title, description: description })
    .map((response: Response) => {
        console.log(response);
    });
  }
}

Similar changes should be made in the authentication.service.ts file as well.

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

Experiencing difficulties accessing Facebook using ngFacebook on angularjs application

I've been working on implementing ngFacebook login into my Angular app, but I'm facing an issue with logging in to Facebook. Even after calling '$facebook.log()', nothing is being displayed in the console. This is a snippet of my Angul ...

Encountering difficulties importing a component from a library into my Nx Expo React Native application

Having an issue with my Nx monorepo which contains an Expo React Native app and various libraries. The problem arises when trying to import a component from a library within the application, resulting in Error: Cannot resolve @monorepo/account-manager Wi ...

Retrieve the properties from within a closure function in a functional component

I have developed a simple React application using create-react-app. The app consists of a single component that takes in a value and an onClick callback. When the callback is triggered, the value increments. import React, { useState } from 'react&apos ...

What is the method to verify if a variable in ES6 is constant?

I'm seeking advice on how to accomplish a specific task. I attempted using the try-catch method, but encountered some limitations: "use strict"; const a = 20; var isConst = false; try { var temp = a; a = a+1; a = temp; } catch (e) { isConst = ...

Updating a session or global variable cannot be read by an AJAX request

Currently using Flask with google-python-api-client for fetching data from Youtube. Experimenting with loading the next video asynchronously from the playlist upon button click. To achieve this, setting the nextPageToken parameter in the request is essent ...

Encountering difficulties with Bootstrap toggle functionality in Angular 2.0 following the establishment of a MEAN stack

While setting up a MEAN stack app following a tutorial, everything was going smoothly until I decided to test some Bootstrap components from their site. After installing Bootstrap in the index.html file for Angular, I noticed that Bootstrap was being loade ...

Changes made to the V-model property will only be reflected after the page is refreshed

I have encountered a situation with two checkboxes that need to reflect the values of watched computed properties. While I can observe reactive changes in my Vue extension when these properties are altered, the updated states of the checkboxes only appear ...

Issue with AngularJS Cross-Origin Resource Sharing (CORS) when making HTTP requests, whereas standard Ajax and jQuery are

I'm currently dealing with a straightforward cross-domain service that is set up to handle Simple CORS requests. When I try to access it using a plain xmlHTTP call or jQuery($.ajax), everything works smoothly. However, when attempting to make the call ...

Troubleshooting SDK Integration with Axeptio in Nuxt3

I am currently developing a Nuxt3 project and I'm looking to integrate a script provided by Axeptio, a cookie platform. To achieve this integration, I created a custom plugin in Nuxt3. export default defineNuxtPlugin((useNuxtApp) => { ;(<any ...

The AgGridModule type does not feature the property 'ɵmod'

Recently, I decided to update my application from Angular 12 to Angular 13. The tools I am using include webpack 5, ag-grid 15.0.0, and ag-grid-angular 15.0.0. While the compilation process goes smoothly for the app, I encountered an issue when trying to l ...

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

Using Vue components alongside vanilla JavaScript code

I am currently working on integrating Vue.js into an existing project that does not utilize Vue. Unfortunately, I have been unable to find any resources or documentation on how to create a Vue component with an API that can be accessed by external code out ...

Angular script error when running 'npm run' on select computers causing Unix command issues for some users but not all

Recently, I've encountered a puzzling issue at my workplace that has been difficult to diagnose. We utilize scripts in npm within the Angular framework to launch a local server instance. Strangely enough, some of my colleagues' computers are thro ...

After stopping the interval with clearInterval(), you can then use the res.send method

I need to continuously log the current date and time to the server console then stop logging after a specified time, returning the final date and time to the user. How do I properly utilize ClearInterval() in this scenario? const express = require(" ...

Proper positioning of popover ensures it does not exceed the boundaries of its parent

In my ngprime table, the header row contains a column field with a popover set to display at the top. However, it is covering the actual field instead of appearing above it. This issue arises because the popover cannot display outside of its parent div, ca ...

Tips for showing JSON information in Nativescript

How can I display all values in a page using the provided JSON data? res { "StatusCode": 0, "StatusMessage": "OK", "StatusDescription": [ { "sensors": [ { "serial": "sensor1", "id": "1" }, ...

An error occurred: Unable to access the 'basemapLayer' property due to it being undefined

Oops! TypeError: Unable to access 'basemapLayer' property of undefined I recently put together a simple application using the Angular CLI. After successfully building and running the application with ng serve -o, I encountered an issue in Chrome ...

Error Encountered with Nested Angular Material Tabs

Is there a way to prevent changes made to the upper tab in md-align-tabs attribute from affecting the inner tab when one tab is nested inside another using md-tabs? If so, how can I achieve this? <md-content layout="column" layout-fill> <md-ta ...

Utilizing JavaScript to Parse Datasnap Output

I am currently working on a project in Delphi where I need to display a list of data in a listbox. However, I am struggling to understand how everything comes together. Luckily, I found a helpful answer that provided me with a solution using a dataset def ...

Referencing an object by using a variable containing its name

I need a way to reference an object using a variable with its name in it. I've figured out how to do this for properties and sub-properties: var req = {body: {jobID: 12}}; console.log(req.body.jobID); //12 var subProperty = "jobID"; cons ...