Utilizing Angular's global interceptor functionality can streamline the process

Having trouble making 2 interceptors (httpInterceptorProviders, jwtInterceptorProviders) work globally in my lazy modules. I have a CoreModule and X number of lazy-loaded modules. Interestingly, autogenerated code by the Swagger generator (HTTP services) gets intercepted, but custom HTTP services do not.

In index.ts where the providers are obtained:

/** Http interceptor providers in outside-in order */
export const httpInterceptorProviders = [
    { provide: HTTP_INTERCEPTORS, useClass: HttpErrorInterceptor, multi: true }
];

export const jwtInterceptorProviders = [
    { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true }
];

In CoreModule, I import my interceptors in the providers section:

@NgModule({
  imports: [
    // angular
    CommonModule,
    HttpClientModule,
    // Rest of the imports...
  ],
  declarations: [],
  providers: [
    // Other service providers...
    httpInterceptorProviders,
    jwtInterceptorProviders,
    // More providers...
  ],
  exports: [TranslateModule]
})
export class CoreModule {
  // Constructor and other functions...
}

// HttpLoaderFactory function definition...

AppModule:

@NgModule({
  // Declarations, imports, bootstrap...
})
export class AppModule {}

Interceptor:

@Injectable()
export class JwtInterceptor implements HttpInterceptor {
    // Interceptor logic implementation...
}

Lazy load module:

@NgModule({
  // Lazy loaded module configuration...
})
export class PetsModule {}

If I export my 2 interceptors in PetsModule, they intercept the requests. However, I want to import them only once in the CoreModule. Check out this example on StackBlitz for reference: StackBlitz Example. Also, make sure to import HttpClientModule only in the CoreModule.

Answer №1

To utilize an interceptor globally with providers in the core module, remember to include `@Injectable({ providedIn: 'root' })` at the top of interceptors as shown in this example: Check out the implementation here.

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 process for using the GitHub API to access a repository's README document?

For my project, I'm utilizing the GitHub API to access the raw README.md file using /repos/{owner}/{repo}/readme. I've successfully executed the call using Thunderclient in VSCode and retrieved the raw file. https://i.sstatic.net/FtkfW.png Howev ...

Is there someone who can explain to me the process behind this?

(function(ng, app){ app = angular.module('app', []); app.config(function($provide) { $provide.constant('town', 'Burlington'); }); app.constant('name', 'Rob F.'); app.controlle ...

Retrieve the parent document for every item within a Firebase collection group

Transitioning from an SQL background to document storage, I am currently navigating through a Firebase database structure that looks like this: John (doc) Restaurant Reviews (collection) Review 1 (doc) Review 2 (doc) Paul (doc) Restaurant Reviews ...

One way to conceal different sections of a Chart.js chart is by clicking on the legend

When using ChartJS, clicking on the legend will make the section disappear. Is it possible to reverse this behavior? For example, when clicking on the legend, all sections in the chart except for the clicked one should disappear. Does anyone have a sugge ...

Guide on integrating the plyr npm module for creating a video player in Angular2

Looking to implement the Plyr npm package in an Angular 6 application to create a versatile video player capable of streaming m3u8 and Youtube videos. The demos on their npm page are written in plain JavaScript, so I need guidance on how to integrate it in ...

Calculate the sum of multiple user-selected items in an array to display the total (using Angular)

Within my project, specifically in summary.component.ts, I have two arrays that are interdependent: state: State[] city: City[] selection: number[] = number The state.ts class looks like this: id: number name: string And the city.ts class is defined as f ...

What is the best way to insert text into a span element within a for loop using JavaScript?

I am currently working on form validation using an array and a loop. In each required field, I have created empty span elements. Here is the JavaScript code that I have set up: var name = document.querySelector('#Name').value, firstLastName = ...

Using the $group operator with a nested array component

Can you show me how to utilize MongoDB's aggregation feature to summarize the count of each reason_id? I have noticed that there are 2 counts for "reason_id = KW7Kcsv7835YZeE3n" and 1 count for "reason_id = KNcKQCjhFzha3oLfE". Below is the dataset: ...

Implement a code to apply to an image that is loaded dynamically

I have a situation on a page where an image is loaded via ajax within a wrapping div. I need to execute some code as soon as that image is loaded. Unfortunately, I am unable to modify the ajax call, which means using on('success') directly on the ...

grabbing data from different domains using jQuery

I attempted to implement cross-domain AJAX examples, but unfortunately, it did not function as expected. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr" lang="fr"> <head> <meta http-equiv="Content-Type" content="text/ht ...

Npm Installation Issue (Dependency Resolution Failure)

Whenever I attempt to execute npm install, I encounter the following error: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfe ...

Automated logout feature will be enabled if no user interaction is detected, prompting a notification dialog box

Here is my working script that I found on this site. After a period of idle time, an alert message will pop up and direct the user to a specific page. However, instead of just the alert message, I would like to implement a dialog box where the user can ch ...

challenges encountered when saving a getjson request as a variable

I am experiencing difficulties in retrieving a variable from a getJSON() request. The issue lies within the following three functions: function getPcLatitude() { // onchange var funcid = "get_postcode_latitude"; var postcode = parseInt($('#i ...

Tips for retrieving console data in VueJS Data

Is there a way to review data from a form component in the console without vue taking any action? I need to receive external data and fill in the fields accordingly. I attempted to set a value using document.getElementsByName("nfe.codigo")[0].value = "000 ...

Issues with $.getjson and trouble with storing JSON data

My current issue involves attempting a getJSON call to a page on my domain that contains a simple JSON array. However, the script in my webpage is not returning anything as expected. <script> $('#genButton').click(function() { ...

Upon clicking the button, the Angular Mat-Table with Reactive Forms fails to display any data, instead adding a blank row accompanied by errors

When the AddRow_click() function is executed, I populate the insuranceFormArray and assign its values to the datasource. However, after adding an entry, an empty row appears in the table, and error messages are displayed in the console. Only a subset of th ...

The typescript MenuProvider for react-native-popup-menu offers a range of IntrinsicAttributes

Looking to implement drop-down options within a Flatlist component, I've utilized the React Native Popup Menu and declared MenuProvider as the entry point in App.tsx. Encountering the following error: Error: Type '{ children: Element[]; }' ...

Updating user data when logged in on multiple browsers can be tricky. Here's how to make sure that

I am currently using the express-session middleware to store user sessions in a Mongo collection. What is the most effective way to update all user sessions when changes are made from one session? For instance, if a user updates their email in session A, ...

`Encountering an unknown index while using AJAX to retrieve data from a PHP file

When using AJax to call a PHP file and retrieve values, I encountered an issue where the called PHP file returns an unidentified variable upon submission. Here is the script being used: <script> function showPrice(str) { if (str == "") { ...

Having trouble with the page layout in AngularJS

I am currently delving into Angular JS in order to fulfill some academic requirements. The issue I am facing is with the rendering of a landing page after successfully logging in through a login portal that caters to three types of users. Strange enough, w ...