Error with reloading AngularJS page while there are still pending HTTP requests

While working on a single-page Angular app and making ongoing HTTP requests, I encountered an issue where if I reload the page before it fully loads, all the error callbacks for the HTTP requests are triggered. This happens when using Google Chrome.

To reproduce this problem, save the following code in an HTML file and reload the page immediately after opening it:

<div ng-app="iceApp" ng-controller="allCharacterController as myCharacter">

<input type="text" id="search1" ng-model="search.name">

  <div ng-repeat="book in myCharacter.character | filter : search">
    {{book.name}}
  </div>
 </div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
 <script type="text/javascript">
 var myApp = angular.module('iceApp', []); 

 myApp.controller('allCharacterController',['$http',function($http) {

 var main = this;
 this.character=[];
 this.baseUrl = 'https://www.anapioficeandfire.com/api/';

  // Loop through 50 pages to get data

 this.allCharacters = function(){
 for(i=1;i<50;i++){

 $http({
    method: 'GET',
    url: main.baseUrl+"characters?page="+i+"&pageSize=50"
  })
  .then(function successCallback(response) {
      console.log(response.data);
      if(response.data.length>0){
          main.character.push.apply(main.character,response.data);
              }

    }, function errorCallback(response) {
      alert("some error occurred. Check the console.");
      console.log(response);
    });
  }

}
  this.allCharacters();

}])
</script>

I am looking for a solution to prevent these error alerts from disrupting the page when multiple HTTP requests are pending. Any help would be greatly appreciated!

For more context, you can visit the actual web application I've been working on here.

Answer №1

HouseService.getAllHouses([i])
.then(function successCallback(response) {

  if(response.data.length>0){
      main.all.push.apply(main.all,response.data);
          }
}, function errorCallback(response) {
  // called asynchronously if an error occurs
  // or server returns response with an error status.
  alert("There was an error. Please check the console.");
  console.log(response);
  //IMPORTANT
  throw response;
});

When a .catch handler fails to re-throw an error, it converts a rejected promise to a successful promise.


To minimize alerts, consider using $q.all for a single rejection handler.

this.retrieveAllHouses = function(){
    var housePromises = [];
    for(let i=1;i<12;i++){
      var promise = HouseService.getAllHouses([i])
        .then(function onSuccess(response) {        
          if(response.data.length>0){
              main.all.push.apply(main.all,response.data);
          }
          return response.data;
      });
      housePromises.push(promise)
    };

    return $q.all(housePromises)       
      .catch( function onRejection(response) {
          // called asynchronously if an error occurs
          // or server returns response with an error status.
          alert("There was an error. Please check the console.");
          console.log(response);
          throw response;
    });
}

Using $q.all, any rejection in promises will lead to rejection of the resultant promise with the first one's rejection value.

This example enhances the retrieveAllHouses function by returning a promise for further chaining.

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

Is there a way to programmatically close Chrome that is running in Kiosk mode?

Currently, I am facing an issue with my Angular 9 app running in Chrome within a Kiosk mode environment. I urgently require a solution to close the Chrome browser as there is no keyboard attached to the PC handling the app. Is there a way to achieve this ...

Avoiding triggering the parent event from the child in React

I'm facing a situation where clicking on a parent element results in it flipping to display a child element with different colors. However, the issue arises when the user tries to click on one of the colors in the child element, as it also triggers th ...

Tips for altering the scrolling rate of a container

I am trying to adjust the scroll speed of specific divs among a group of 5 divs. I came across a solution that changes the scroll speed for the entire document: http://jsfiddle.net/36dp03ur/ However, what I really need is a scenario like this: <div i ...

What is the best way to link the width and height of a div with form fields?

I need to implement a feature where I can create multiple div elements that are draggable and resizable, and have their properties like width, height, etc. linked to corresponding objects in an array. For example, if I create six divs, there should be six ...

js variables are discovered to be without defined values

I am currently working on building a contact form using a modal with a partial view in the .Net framework. Everything is functioning except for the JavaScript part. I am facing problems with getting the js to recognize cuLink and cuLinkClass. The Contact ...

show the attributes of an item contained within an array of objects

Hey there! I'm facing an issue with displaying the content of an object on my HTML page using React. So, here's what's happening: I can access the frontend properties in my object array, but when I try to loop through each element and displa ...

Determine the total number of values within a specific Object

const obj1 = { 1: 'a', 2: 'b', 3: 'a', 4: 'c', 5: 'a', 6: 'd', 7: 'c', }; The desired output for the given code should be: output = { a: 3, b: 1, c: 2, d: 1 } ...

"AngularJS offers a unique way to include alternative text in placeholders and titles using

I need to implement an input field (<input..>) with a placeholder and title for tooltip that functions in the following way: There is a variable called "myString" which can either be undefined/empty or contain a string. When empty, a default string ...

I require assistance in configuring the timing for an animation using Jquery

How can I adjust the timing (delay between two words) for this animation? If you need help, you can check out this link for guidance. Feel free to share your suggestions! ...

There is a JSON issue present, with half of the variables being undefined

Having an issue with my JSON as it throws me an undefined error. What's puzzling is that it recognizes my first variable without any problem. Below are the codes for better understanding: JSON {"Comics":[ {"comic" : { "src":"Pictures/Comic ...

Purge POST request cache in Node.js

Currently, I have implemented nodemailer to enable users to contact me via email. Once the form data is submitted successfully, the page redirects to my homepage as intended. However, if an attempt is made to refresh the page, a confirmation alert pops up ...

Remove an item from a complex JSON structure based on the specified name. The function will then return the

Hey there, I'm just starting out with react native and I have an array of objects. My goal is to remove an inner object from this JSON data. [ { Key: 1, exchnageArr: [ { name: ”FX” }, { name: ”MK” ...

Choose the following element of a specified category after a designated element

In my current project, I am faced with the challenge of selecting an element based on the presence of another element with a specific ID that contains certain text. The complication arises from the fact that there are multiple elements sharing the same cla ...

Issue with accessing global variable in nested function using "this" in Angular 2

Having recently delved into Angular 2, I find myself facing a challenge with accessing the "task_title" within the startTimer() function. The console.log() returns undefined and I suspect it's due to "this" referring to the function itself instead of ...

Navigate to the top of the page prior to updating the Link route in NextJS

Whenever I click on a link to navigate to a new page, the page loads and immediately scrolls to the top. I want to change this behavior so that the scroll resets to the top before the new page is rendered. You can observe this issue on . If you scroll do ...

The functionality of jQuery smooth scrolling to an anchor is only effective when the page is at the top and there is

Currently, I am working on designing a simple one-page website featuring a fixed menu that smoothly scrolls to specific sections on the page upon clicking the menu items. However, I have encountered an issue where the scrolling works perfectly only when t ...

Transforming the current date() into a distinctive format, encompassing the utilization of T

Background In my Angular UI, I have a datepicker that is defined as: <date-picker name="contractEndDate" date="employee.contractEndDate"></date-picker> When the button is clicked, the contractEndDate value changes from null to the current da ...

Using the AngularJS component, one can easily implement the $translate feature

I am currently working on integrating the $translate.proposedLanguage() function into an AngularJS component to set up and configure the intl-tel-input plugin: function customTel() { return { restrict: 'A', // restriction as Attr require ...

I must retrieve cookies from the GET call API within the route.js file

I've developed a website using Next.js 13 with a route called /api/users/me. In this route, I need to access the cookies to extract the token. While calling the API from the browser gives me the desired result, trying to call it from the frontend page ...

AngularJS failing to display HTML content is a common issue encountered

I am a beginner in Angular JS and recently wrote a simple Angular code. However, I am encountering issues with the HTML rendering incorrectly or the expressions not getting evaluated. I could use some help identifying what I might be missing. The version ...