Capture all HTTP requests made by Angular2

I'm trying to find a way to intercept and modify all HTTP requests made by Angular by adding custom headers. In previous releases prior to angular2 RC5, this was achieved by extending the BaseRequestOptions like this:

class MyOptions extends BaseRequestOptions {
    Authorization: string = 'Bearer ' + localStorage.getItem('tokenName');
}

bootstrap(AppComponent,
    [HTTP_PROVIDERS,
        { provide: RequestOptions, useClass: MyOptions },
    appRouterProviders,
    disableDeprecatedForms(),
    provideForms(),
]).catch(err => console.error(err));

Currently using version 2.0 final, I found a suggestion on how to implement this in the newer version which looks something like this:

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ AppComponent ],
  providers: [
    { provide: RequestOptions, useClass: MyOptions }
  ],
  bootstrap: [ AppComponent ]
})
export class AppModule {
}

@Injectable()
export class MyOptions extends RequestOptions {
  constructor() { super({method: RequestMethod.Get, headers: new Headers()}); }
}

However, when implementing this, an error is thrown:

TypeError: Can not read property 'merge' of null
. Check out this example for more details.

Note: The implementation of MyOptions mirrors that of BaseRequestOptions, as copying it resolves the issue. View this example for comparison.

Answer №1

I found a couple of errors in your script

  • You forgot to include RequestMethod

  • Make sure you define your extended class MyOptions before using the NgModule decorator

If you make these corrections, your demonstration will resemble the one on Plunker

Answer №2

For further information on this topic, feel free to explore the following StackOverflow questions:

Exploring the Equivalents of HTTPInterceptor in Angular2

Understanding Interceptors in Angular2

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

Creating a dedicated class or module specifically designed for handling import and export tasks is a highly efficient approach towards stream

Exploring different ways to import multiple classes into a single class file: import myClass1 'pathto1'; import myClass2 'pathto2'; import myClassn 'pathton'; Seeking a simpler method using one file (class export) with al ...

RouterLink element

The RouterLink directive selector specified in the official documentation is :not(a):not(area)[routerLink]. This means that it will select all elements with a routerLink attribute that are not anchor or area elements. Is my understanding correct? Given th ...

Currently in the process of configuring an ionic project, encountering a series of errors upon executing the npm install command

gyp ERR! configure error gyp ERR! stack Error: Unable to locate Python executable "python", please set the PYTHON environment variable. gyp ERR! stack at PythonFinder.failNoPython (C:\Program Files\nodejs\node_modules\npm\node_ ...

The Vue application combined with TypeScript is displaying an empty white screen

I've enrolled in a Vue + Firestore course, but I'm attempting to use TypeScript instead of conventional JavaScript. The basic setup is complete, however, my app displays a blank page when it should be showing a simple header text from the App.vue ...

Uploading Multipart Files and JSON Data using Spring Boot

I am looking to create an API using Spring Boot for uploading a multipart file as part of the JSON body, and also to save the image URL in a database. The requests will have the following format: ------WebKitFormBoundarynBsAcX7rJhOGsmfY Content-Dispositio ...

Eliminating the nested API call within a loop

After making an API call to retrieve a set of data such as a list of users, I noticed that I am implementing a for loop and within it, I am making another API call to obtain each user's profile details based on their ID. I understand that this approac ...

Challenges arise when dealing with generics in TypeScript

I'm a beginner in TypeScript and I'm trying to write a method with a generic type argument similar to what you can do in .Net. Here's the code snippet I've been working on: class TestObject { Id: number; Truc: string; Machin: str ...

Upgrading from Angular 5.2 to 6.0: Facing an issue where angular.json does not replace angular-cli.json

After diligently following the official documentation to upgrade from Angular 5.2 to Angular 6.0 (with the end goal of migrating to Angular 13), I found myself at a standstill. Executing the command NG_DISABLE_VERSION_CHECK=1 npx @angular/cli@6 update @an ...

Angular's server-side routing is essential for custom localization functionality

I am currently working on localizing my Angular app. All the displayed values are stored in a single json file (stringResources.json). After translation, I will have individual files for each supported language (e.g. en.json, fr.json, etc). Since I utilize ...

How to eliminate file nesting in Visual Studio 2017

Is there a way to prevent certain file types from being nested within other files, such as .ts files not being nested beneath .html files? I came across this request, but has anyone found a solution to achieve this? ...

You must include an argument for 'model' in the Angular service

My service requires an id parameter for a route, but when I tried to access the route with the id, I encountered the error mentioned above. Any suggestions on how to resolve this issue? https://i.sstatic.net/FEcqo.png #request const apiBaseUrl = `${envir ...

Develop Connective Plugins using Angular 12

I am working on implementing a new feature for my app that involves storing certain modules on the backend and loading them dynamically based on user demand. Instead of loading all modules at once, I want to only load the necessary modules just before the ...

"Mastering the art of debouncing in Angular using

I am facing an issue where, during a slow internet connection, users can press the save button multiple times resulting in saving multiple sets of data. This problem doesn't occur when working locally, but it does happen on our staging environment. E ...

Issue with displaying options in Angular2 v2.4.9 HTML select element

Ever since I made the transition from AngularJS to Angular2, I've been facing a peculiar issue. The select element's options data is fetched from a Solr query, which always returns a 200 response with the data in a timely manner. However, the pr ...

Adding a parameter to each route by default."

In my Angular app, the route structure is as follows: const routes: Routes = [ { path: ':lang', children: [ { path: 'home', component: HomeComponent }, { path: 'dashboard', component: DashboardC ...

Difficulty accessing class functions from the test application in Node.js NPM and Typescript

I created an NPM package to easily reuse a class. The package installs correctly and I can load the class, but unfortunately I am unable to access functions within the class. My project is built using TypeScript which compiles into a JavaScript class: For ...

Pinia store encountering a Typescript Vue component issue: error message "The property 'testStore' does not exist on the 'CreateComponentPublicInstance' type."

Within my <script setup> block, I have imported my testStore. However, whenever I attempt to use this.testStore.name in my Vue file, Vetur displays the following error: Property 'testStore' does not exist on type 'CreateComponentPublic ...

Using an Angular HttpClient to authenticate with an API by utilizing a token for

I am currently attempting to fetch data from my Jenkins JSON API via HTTPClient. The data I need access to is restricted, so I must authenticate against Jenkins. To do this, I have generated an API Token. However, I am unsure of how to authenticate myself ...

Ways to dynamically authenticate in AuthGuard and return a true value

I am working on an auth guard that has multiple conditions, and I am looking for a way to dynamically return a true value. Here is the relevant code snippet: auth.guard.ts canLoad(route: Route, segments: UrlSegment[]): Observable<boolean>|Promise&l ...

Angular2 - adding the authentication token to request headers

Within my Angular 2 application, I am faced with the task of authenticating every request by including a token in the header. A service has been set up to handle the creation of request headers and insertion of the token. The dilemma arises from the fact t ...