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

Update the content of a div element with the data retrieved through an Ajax response

I am attempting to update the inner HTML of a div after a certain interval. I am receiving the correct response using Ajax, but I am struggling to replace the inner HTML of the selected element with the Ajax response. What could be wrong with my code? HTM ...

incorrect choice of ngClass

Having sifted through numerous queries, I have come to this realization... The angular [ngClass] is behaving oddly when it comes to values like 10, 24, and 100. I can't seem to figure out the reason behind this behavior. Perhaps someone here might be ...

Nodemon has encountered an issue: Unable to listen on port 5000. The address is already in use

During the creation of my project with nodejs and express for the backend, everything was running smoothly. However, whenever I made changes to a file, nodemon would encounter an error preventing the server from restarting: Error: listen EADDRINUSE: addre ...

No data is being returned by the Jquery Ajax function

I am experiencing an issue with a Jquery Ajax call in my code: $('body').on('click', '#btnPopulate', function() { alert(getTree()); }); function getTree() { var url = getUrlPath() + "/StoryboardAdmin/BuildStoryboardViewMode ...

Having trouble with integrating user input from HTML into a JavaScript file to execute a GET request

I am currently working on a project to create a website that integrates the google books API for users to search for books. To start, I have set up a server using express in index.js at the root of the project directory, and all my static files are stored ...

VueJS added a new object to the array, but the data did not update reactively

Here is my current data layout days: [ { id: 0 name: 'Monday', times: [] }, { id: 1 name: 'Tuesday', times: [] } } I have implemented the following function to append an object to the times array. onT ...

Modify the properties of an element based on another

Situation : I am facing a challenge where I need to adjust two components based on a click event. The function linked to the onclick event handleChange includes a prop 'text'. Each time the onclick event is triggered, I must modify the value of t ...

Finding the length of a filter in an AngularJS directive

I'm trying to figure out how to retrieve the value of filtered.length within my custom directive called my-dir. <li my-dir ng-repeat="result in filtered = (results | filter:query | orderBy: 'title')"> <h1>{{ result.title }}& ...

Every time Lodash.uniqueId is called, it consistently generates the value of

Consider using the lodash library, specifically version 4.17.11. _.uniqueId() seems to consistently output 1 instead of a random three-digit number. Similarly, _.uniqueId('prefix') always returns prefix1. Do you see this as a potential issue? ...

Could you explain the distinction between these two arrow functions?

I'm puzzled about why the second arrow function is effective while the first one isn't. //the first one doesn't function properly this.setState = () => { text: e.target.value, }; //in contrast, this one ...

Having trouble sending JSON data to the server using a POST request

I am encountering an issue while attempting to send JSON data to the server using the fetch API and PHP as the server-side language. The PHP code on the server side is quite simple: <?php header("Access-Control-Allow-Origin: *"); header("Access ...

What is the minimum number of lines that can be used for javascript code?

Currently, I am in the process of developing a custom JavaScript minifier. One question that has come up is whether it is necessary to insert line breaks after a certain number of characters on a single line, or if it even makes a difference at all? For i ...

AngularJS - the element of surprise in execution sequence

Encountering a puzzling issue that exclusively affects Internet Explorer (any version) and not Chrome. An "items" array is stored within the "doc" object. Users have the capability to edit items, which essentially deletes the item but retains its content ...

I keep encountering a parser error when making an AJAX call to retrieve JSON data. It seems to be caused by

here is a snippet of code I am working on $.ajax({ type: 'GET', url: "<%=request.getContextPath()%>/manageUsers.do", cache: false, data:{ "resultType": "json", "submit": $.i18n.prop('esadmin.manage.users ...

Is a package.json file missing dependencies?

Curious about the meaning of peerDependencies, I examined the contents of this package.json file. It relates to a library project that is distributed elsewhere. { "name": "...", "version": "...", "description": "...", "author": "...", ...

Create an HTML button on the homepage that directs users to the "about" page

I've been struggling to make a button in my Ionic app navigate to a different page upon clicking. Despite being new to Ionic, I've spent hours trying to solve this issue. Below is the HTML code in home.page.html: <ion-header> &l ...

Creating instance methods in a TypeScript object can be accomplished by defining the methods within the object's class definition. When the object is

As a seasoned Java developer, I've recently been dabbling in TypeScript. Let me introduce you to my user object: export class User { id: string; name: string; email?: string; unit: string; street: string; postalcode: string; ...

Is there a way to modify the edit button to become a save button and include a cancel button?

Is there a way to toggle between an edit button and a save button, along with a cancel option? $('#edit').click(function() { $(this).hide(); $('#save, #cancel').show(); }); $('#cancel').click(function() { $('#ed ...

Utilizing a function as an argument in another function (with specified parameters)

I’m stuck and can’t seem to solve this problem. In my function, the parameter filter needs to be a function call that accepts an object created within the same function: function bindSlider(time, filter) { var values = { min : 8, max : ...

I am having trouble with retrieving and showing Json data in a table using axios within a React component

Struggling to access JSON data using hooks to display it in the <p> tag but encountering an error - "TypeError: states.map is not a function". I attempted utilizing Array.from() to convert my JSON to an array, yet it neither displayed anything nor pr ...