A specialized HTTP interceptor designed for individual APIs

Hey there, I am currently working with 3 different APIs that require unique auth tokens for authentication. My goal is to set up 3 separate HTTP interceptors, one for each API. While I'm familiar with creating a generic httpInterceptor for the entire project, I'm unsure of how to create distinct interceptors for each individual API service. Can you provide some guidance on this?

Answer №1

To handle multiple paths with different tokens, you can utilize a single interceptor in Angular. This interceptor allows you to access the URL and apply specific token logic based on the path. Here's an example implementation:

        intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
          let token;
          
          if (request.url.indexOf(PATH_ROUTE_ONE) !== -1) {
            token =  localStorage.getItem(TK1);
          } else if(request.url.indexOf(PATH_ROUTE_TWO) !== -1) {
            token =  localStorage.getItem(TK2);
          } else {
            token =  localStorage.getItem(TK3);
          }

          if (token) {
            request = request.clone({
              setHeaders: {
                authorization: `Bearer ${token}`,
              },
            });
          }

          return next.handle(request).pipe(
            tap((res) => {
              if (res instanceof HttpResponse) {
                // TODO: Update token info
              }
            }),
            catchError((err: HttpErrorResponse) => throwError(err)),
          );
        }

If you need to handle three different paths with unique tokens, you can extend this approach by adding additional conditions in the interceptor. By reading the URL, you can determine which token to use for each path.

       intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
          let token = localStorage.getItem(TK1)
          
          if (request.url.indexOf(PATH_ROUTE_ONE) !== -1) {
            request = request.clone({
              setHeaders: {
                authorization: `Bearer ${token}`,
              },
            });
          }

          return next.handle(request).pipe(
            tap((res) => {
              if (res instanceof HttpResponse) {
                // TO-DO: Update token info
              }
            }),
            catchError((err: HttpErrorResponse) => throwError(err)),
          );
        }

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

Spotlight a newly generated element produced by the*ngFor directive within Angular 2

In my application, I have a collection of words that are displayed or hidden using *ngFor based on their 'hidden' property. You can view the example on Plunker. The issue arises when the word list becomes extensive, making it challenging to ide ...

A guide on managing Ngb Bootstrap carousel slide with a button in Angular

I encountered a situation like this: I need to implement a Ngb Bootstrap carousel with buttons for Previous and Next to control the slide images. Clicking on the Previous button should display the previous slide image, and clicking on the Next button shou ...

Determining when ng-repeat has completed in Angular JS

Is there a way to determine when ng-repeat has completed populating the values in the markup? Since I have numerous values, it may take some time for the rendering process. NG <ul > <li data-ng-repeat="item in values"> ...

Empty array returned on click using Angular 5 with chart.js

I've been struggling with getting the onclick function in chart.js to work properly. I came across the getElementsAtEvent(event) function which should supposedly return an array containing the data of the clicked part of the chart. However, all it ret ...

Displaying Data in React Table from JavaScript Object

I'm working on a React component that will display a table of data from a JavaScript object called pixarMovies. The initial state is set with this object. My goal is to sort the movies chronologically by date and render them in a table format (refer t ...

Tips for efficiently storing data in the Laravel database using Ajax

I'm attempting to upload a product with multiple images to the database without refreshing the page. Despite not encountering any errors in the console, I am seeing a long block of text that starts like this: <script> Sfdump = window.Sfdump || ...

Error encountered while trying to call callback functions

I encountered an error in my code, but I managed to resolve it independently. Could someone please provide an explanation of why the code wasn't working and delve into the mechanics behind the issue? Here is the code snippet: var listTables = functi ...

How to use React MUI Checkbox to set the checked value as false

I'm encountering an issue with the React MUI - Checkbox component. On my site, I have a checkbox linked to a handler that targets a REST API endpoint. This endpoint sets a boolean flag for the user in the database on a POST request and returns the boo ...

Is it possible to bind computed values in Ember using .properties(...) with ember-model?

I'm attempting to utilize the .property('key') syntax in order to update a computed value within my model. The structure of my model is as follows: App.Camera = Em.Model.extend({ id: attr(), uid: attr(), name: attr(), type: ...

Property of object (TS) cannot be accessed

My question relates to a piece of TypeScript code Here is the code snippet: export function load_form_actions() { $('#step_2_form').on('ajax:before', function(data) { $('#step_2_submit_btn').hide(); $(&ap ...

Utilizing the JSON.parse method in JavaScript in conjunction with an Ajax request while incorporating the escape character "\n" for new line functionality

https://jsbin.com/zuhatujoqo/1/edit?js,console Edit: json file has this line: {"pd":"ciao \\n ste"} I need to retrieve a valid JSON file through an ajax call. Then parse the result using JSON.parse. I'm confused about the behavior of t ...

The AJAX event is failing to send data

When using two ajax calls, the first one populates a dropdown box successfully. However, the second ajax call utilizes a change event function to list product details with images whenever a dynamically populated item from the dropdown is clicked. In the c ...

Updating the log file location for electron-log in an Angular application integrated with Electron

I am currently developing a project using Angular 6 integrated with Electron. I have managed to successfully incorporate the electron-log library using ngx-electron. As a result, my application is functioning well and logging data to the default path: C:&b ...

Troubleshooting issue with error handling in graphql mutation hook with react and apollo is not resolving

It seems like I might have overlooked a configuration in my code, but I can't seem to pinpoint where I went wrong. In our application, we have a basic login form. If the correct username and password are entered, everything works smoothly. However, ...

What could be causing the directives module to not get properly incorporated into the Angular app module?

I am currently in the process of learning Angular and have come across some challenges with module resolution. In js/directives/directives.js, I have a directive scoped within a directives module: angular.module("directives").directive("selectList", funct ...

Implement the AngularJS orderby filter based on a checkbox selection

Is it possible to use the angularJS orderby filter with a checkbox for ordering columns? I currently have this working as expected: <tr ng-repeat="player in players | orderBy:'id':true | rangeFilter:min:max"> <td>{{player.id}}</ ...

Tips for preserving scroll position within a division following the redisplay of a division in Vue.js

Within my Laravel and Vue project, I have set up a feature to display posts in a scrollable area. This area is only visible when the 'showFeed' variable is true. <div v-show="showFeed" class="scroll-container" v-scroll=&quo ...

The React Material Component stubbornly resists being horizontally aligned in the Code Sandbox

Currently, I am working on getting my Material design to function properly within the CodeSandbox environment. One issue I am encountering is attempting to center it horizontally. As of now, it appears like this: To make it easier to identify its locati ...

Utilizing Typescript for manipulation of Javascript objects

Currently, I am working on a project using Node.js. Within one of my JavaScript files, I have the following object: function Person { this.name = 'Peter', this.lastname = 'Cesar', this.age = 23 } I am trying to create an instanc ...

Is it necessary to include parentheses when utilizing a named function as a jQuery ajax success callback?

Is it necessary to include parentheses when specifying a function as a success callback if it was defined earlier? What impact does including or not including parentheses have? For example: function fish_food(){//do something} $.ajax({ url: '/ ...