Execute AngularJS $resource request to alternative URL if no response received within specified time frame

In the event that my primary API is unresponsive, I want my front-end application to automatically switch to a secondary API.

For instance, when calling results in a net::ERR_CONNECTION_TIMED_OUT error (as seen in Chrome XHR response), signifying that the primary API is down, I would like the front-end to then call .

I have reviewed the documentation for AngularJS 1.5.7 $resource, which mentions an action parameter timeout of type {number}. However, even setting it to 500 still triggers the net::ERR_CONNECTION_TIMED_OUT after around 2 minutes!

Desired workflow:

  1. Make request to
  2. If no response within 10 seconds:
    • Switch to
  3. Continue switching between APIs as long as backends are available

Pseudocode:

angular.forEach(fallback_urls, function(url) {
  $resource(url + '/users?name=bob', {}, {timeout: 10}).get()
});

Answer №1

Your actions on the $resource may need to be reviewed.

$resource(url + '/users?name=bob', {}, {
    'get': {
        method: 'GET',
        timeout: 10000
     }
});

Consider exploring the "cancellable" option as well.

var res = $resource(url + '/users?name=bob', {}, {
  'get': {
    method: 'GET',
    cancellable: true
  }
});

var response = res.get();
var timeoutPromise = $timeout(function(){
    response.$cancelRequest();
},10000);

response.$promise.then(function(){
    $timeout.cancel(timeoutPromise);
});

Iterate through your backup $resource declarations in a systematic way. Remember to abort the timeout if the call is successful! Hopefully, these hints will guide you in the right direction!

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

Disregard any unrecognized variables associated with the third-party package

I've been working on integrating the bluesnap payment gateway into a react/ts project. I added their hosted javascript code to my public/index.html and started the integration within a component. However, when compiling, an error pops up saying ' ...

Is it possible to utilize the key from ng-repeat within a model for another purpose?

Is there a way to use the ng-repeat key as part of the ng-model for an input field in AngularJS? Here is an example of what I am trying to achieve: <div ng-repeat="(key, val) in $ctrl.offer.properties"> <fieldset ng-if="val"> <h3> ...

Switch out the specific content within the p tag

Looking to update the highlighted text within a p tag. The code below addresses handling new line characters, but for some reason the replacement is not working as expected. Check out the HTML snippet: <p id="1-pagedata"> (d) 3 sdsdsd random: Subj ...

What is the best way to use jQuery to toggle the hidden class on an inner div when a button inside a card is clicked?

How can I implement jQuery functionality to toggle the hidden class on an inner div by clicking a button inside a card? I attempted to create a container div containing multiple cards. The issue arises when I click the button - it only opens the panel, bu ...

What is the best way to eliminate a count from an array when a button is deselected using JavaScript?

Whenever a button is selected, the value appears on the console.log as expected when using an array. To enhance this functionality, I also need to find a way to remove the value from the console when the button is deselected. var totalWishlist = []; $( ...

How to link an external CSS file to a Vue.js project

I created a new project using @vue/cli and now I want to add an external CSS file to my App.vue Here's what I attempted: <template> <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | ...

What is preventing this setTimeout from triggering?

My experience with Knockout js has left me puzzled, as I seem to be missing a key concept. Despite no error messages, it's challenging for me to pinpoint where exactly the issue lies. All I want is to periodically fetch data and update my table using ...

The functionality of event.charCode is ineffective in Firefox

I'm in a dilemma with restricting my text field to only accept numbers. Currently, I have the following code snippet: onkeypress="return (event.charCode >= 48 && event.charCode <= 57)" The issue arises when I attempt to delete (using b ...

It is not possible to include a new property to an object while inside a function

Looking to add a property to an object? Check out the code below: import React from 'react'; import { Link } from 'react-router-dom'; const Question = () => { let active; const handleClick = (iconName) => { active = {}; ...

Testing Angular 2: Ensuring Component Properly Calls Router with Accurate Arguments

I'm facing an issue with a child component that includes a button element with 'routerlink' attribute for navigation upon clicking. The button does not have a '(click)' handler, only the routerlink. Currently, I am writing a unit ...

Transform the structure of the JSON data object

When I use the fetch() request, a JSON file is displayed. Here's an example of what I receive from the database: [ { "id": 3086206, "title": "General specifications" }, { "id": 3086207, "title": "Features ...

Having issues with accessing data from Informix database in PHP due to an undefined index?

I am encountering the following error multiple times per row: Notice: Undefined index: enviopre in /opt/lampp/htdocs/pruebax/pruebaxone.php on line 34 Notice: Undefined index: enviofra in /opt/lampp/htdocs/pruebax/pruebaxone.php on line 35 Notice: Undef ...

Conceal Bootstrap Toast for a day following dismissal

I have implemented Bootstrap 5 toasts to showcase an advertisement on my website. The goal is to make the advertisement disappear for 24 hours once the user closes it. Here's the current code snippet: <div class="position-sticky bottom-0" ...

Is it possible to determine if a JavaScript/jQuery effect or plugin will function on iPhone and iPad without actually owning those devices?

Is there a way to ensure that a javascript/jquery effect or plugin that works well on all desktop browsers will also work on iPhone and iPad without actually owning those devices? Can I rely on testing it on the latest Safari for Windows to guarantee comp ...

Creating a custom backdrop for your kaboom.js webpage

I created a kaboom.js application and I'm having trouble setting a background for it. I've searched online extensively and attempted different methods on my own, but nothing seems to be working. (StackOverflow flagged my post as mostly code so I ...

Is there a way for me to utilize the imported data from one component in the context API using an arrow function?

I am trying to utilize placeInfo, reviews, detailsInfo, news from a data file. Instead of using value='hello', I am unsure if I can directly use it like this: value={placeInfo, reviews, detailsInfo, news}, as it is producing an error. Should I st ...

Tips for sending information from a controller to jQuery (Ajax) in CodeIgniter

Code snippet in controller: $rates['poor'] = 10; $rates['fair'] = 20; $this->load->view('search_result2', $rates); //Although I have attempted different ways, the only successful method is using the code above. Other ...

Is it possible to utilize viewport height as a trigger for classes in Gatsby?

Unique Case Working on a Gatsby site with Tailwind CSS has brought to light an interesting challenge regarding different types of content. While the blog pages fill the entire viewport and offer scrolling options for overflowing content, other pages with ...

What is the method to prolong the end date of fullCalendar.js through Javascript?

I am facing the same issue as this individual. I am unsure of how to add one day to the end date. I do not want to alter the database value, only modify it on the HTML page. Currently, this is my calendar (no Moment.js joke intended): $(document).ready(f ...

Switch app engines in real-time based on the URL path with express framework

How can I dynamically set App Engine based on the URL? In my application, I have two render engines available: serverSideRenderEngine & browserRenderEngine If the URL is /home, the app.engine should be set as serverSideRenderEngine If the URL is /l ...