Creating a custom AngularJS HTTP interceptor that targets specific URLs

Is there a way to configure an $http interceptor to only respond to specific URL patterns?

For example, I want the interceptor to only intercept requests that match "/api/*" and ignore any other requests.

Answer №1

To manage errors in requests and responses for URLs that begin with "math/", you can filter the URL in both success and rejection functions.

Below is an interceptor example:

$httpProvider.interceptors.push(function($q, mathError) {
    return {
        requestError: function(rejection){                            
            mathError.anyError(rejection);    
            return $q.reject(rejection);
        },
        responseError: function(rejection){                            
            mathError.anyError(rejection);
            return $q.reject(rejection);
        }
    };
});

Here is a factory where you can handle these errors:

myApp.factory('mathError', function(){
    return {
        anyError: function(rejection){ 
            if (rejection.config.url.substr(0, 5) === "math/") {
                console.log("Only Math errors are handled here"); 

                //Implement custom error handling
            }
        }         
    };
});

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

Using socket.io to filter MongoDB documents by their unique object IDs

I am facing an issue where I need to retrieve a specific document from a MongoDB collection using the object ID when working with Socket.io. Since `findById()` is not effective in this case, and I am unable to use `find({ "_id" : _id})`, I am unsure about ...

Iterate through a collection of nested objects and check them against an object contained within an array

I'm facing a frustrating issue in Firebase where I am required to compare an object returned to me with an array. I need assistance in completing this method: const removeAlreadySeenUsersFromQueue = (newUsers, likedUsers) => { } The scenario is ...

Regular expressions - For alphanumeric or numeric with a possible slash character included

I need assistance with extracting alphanumeric values from a string array using RegEx. For instance: Apartment 101/B First Villa 3324/A Second Milk 12MG/ML Third Sodium 0.00205MG/ML Fourth Water 0.00205MG Fifth Eggs 100 Sixth My goal is to retrieve the v ...

Puppeteer: How to wait for an ajax call to complete after a navigation event

When working with my code, I encounter a situation where I need to submit a form, wait for navigation, and then submit a second form. The challenge arises because before submitting the second form, some data needs to be loaded in the form using ajax. I wa ...

Using percentages to position Div elements

Currently, I am working on an HTML page that requires a div element spanning the full width of the page. My goal is to arrange other divs within this full-width div using percentages rather than pixels. The class associated with this div is .question. Thi ...

Ensure all asynchronous Ajax requests have completed before considering the page fully loaded

Many websites, such as YouTube, load the majority of their content after the DOM is ready using JavaScript. How can I ensure that all of these requests have been completed before injecting my code? window.onload = function() {}; The above code snippet do ...

Error with decodeURIComponent function in Internet Explorer 8

My widget, loaded as an iframe, requires data about the hosting page. I have UTF-8 strings extracted from a page with Russian text. The page itself has proper HTML5 doctype and meta charset. This is how my code operates: params = "x1=" + encodeURICompone ...

Guide on replacing placeholders in a text with input fields and connecting them with v-model in Vue.js

I am currently working on creating an exam page that features fill in the gap type questions. These questions have placeholders where students need to insert the correct words or phrases. The questions are fetched via an ajax request and consist of simple ...

Employing the ng-token-auth function for logging in and submitting to an alternate URL

Currently, I am utilizing ng-token-auth along with angular/ionic to interact with a rails api. My focus right now is on the login page where I have implemented the following form: <form ng-submit="submitLogin(loginForm)" role="form" ng-init="loginForm ...

The Vue template syntax utilizes double curly braces for incrementing values within must

Embarked on learning Vue.js recently and I am intrigued by the unusual behavior in my simple code. I cannot seem to figure out what is going wrong. I am attempting to increment a counter inside mustache syntax, but something strange is happening with this ...

Strategies for organizing your week with a calendar

Hello, I am working on creating a weekly calendar using PHP and I want to add events to the calendar like in this example. However, I am unsure how to display the events in the calendar at the correct time of day. Here is the code snippet I am currently u ...

Is it possible to retrieve JSON data and display only the entries with positive values in an HTML

I am working on a project that involves fetching JSON API data and displaying it in an HTML table, but only for values above 10. Below is the code snippet along with my JavaScript. I specifically want to exclude negative values and only display positive v ...

Tips for extracting HTML entities from a string without altering the HTML tags

I need assistance with removing HTML tags from a string while preserving html entities like &nbps; & é < etc.. Currently, I am using the following method: stringWithTag = "<i> I want to keep my ->&nbsp;<- element space, bu ...

Modifying HTML attributes using AngularJS

Is there a straightforward method to dynamically alter an HTML attribute? I've used Angular's scope variable and ng-hide to hide a div, but the size of the div remains unchanged. How can I adjust the size of that particular div? I attempted th ...

Utilize Node.js to sort through data

One API is providing me with this type of response. I need to extract the latitude and longitude of a single entity. How can I filter this data using JavaScript (Node.js)? header { gtfs_realtime_version: "1.0" incrementality: FULL_DATASET timestamp: ...

Utilizing a Bootstrap 3 modal within an AngularJS application with html5mode

How to display Bootstrap Modal in the first click when using html5Mode(true). When clicking on launch demo modal, the URL changes to /#myModal upon the 1st click but the modal does not appear. The modal only appears upon clicking launch demo modal again. ...

I am having issues with the Load More Posts Ajax Button on my WordPress site and it is

I'm trying to display more posts when a button is clicked. Upon inspecting and checking the network, everything seems to be working fine, or at least that's what I assume. https://i.sstatic.net/44VS1.jpg https://i.sstatic.net/KEkiz.jpg I&apos ...

Accessing the index in an Angular ngFor loop allows for

Is there a way to access the index within ngFor in Angular? Check out this link for more information. Appreciate any help! Thank you. ...

In order to ensure that the multiselect bootstrap dropdown options drop outside of the div and prevent scroll bubbling, there are specific

I am trying to customize a bootstrap multiselect dropdown located within a div. You can find an example of what I'm working on at this link: http://jsfiddle.net/The_Outsider/8watL2L1/9/ In my design, I want the multiselect dropdown options to drop ou ...

Check for equality with an array of objects when reacting to changes

I have an input field and an array of objects. I want the object with a property named "airplaneCompany" to be displayed as I type. Each character should be checked, and if the object's "airplaneCompany" property starts with 'a', it should b ...