What is the best way to retry an HTTP call in AngularJS when the response data is null but the response status is

One issue I am encountering is when the server sends back empty XML without any data. Although most of the time everything works smoothly and as expected, sometimes this emptiness causes problems in processing the response.

var isokLayer = $http({
        method: 'GET',
        url: URLs.GEOSERVER_ISOK
    }).then(function(response) {
        if (response.status == 200) {
            do {
                var formatter = new ol.format.WMTSCapabilities();
            } while (response.data == null);

            var datas = (formatter.read(response.data));

            var options = ol.source.WMTS.optionsFromCapabilities(datas, {
                layer: 'CIEN',
                matrixSet: 'EPSG:2180',
            });
            var source = new ol.source.WMTS(options);

            for (var z = 0; z < source.getTileGrid().getMatrixIds().length; ++z) {
                source.getTileGrid().getOrigin(z).reverse(); 
            }

            var result = new ol.layer.Tile({
                source: source,
                visible: false,
                xarisLayerType: 'baseLayer',
                xarisLayerName: 'NMT LPIS',
                xarisLayerSampleIcon: 'assets/styles/img/baseLayerSample/nmt.png',
                zIndex: ConfigService.getBaseLayerZIndex()
            });
            map.addLayer(result);
            layerList.push(result);
        } else {
            console.log(response.status);
        }
    }, function(err) {
        console.log(err);
    });

I'm looking for a way to repeat the HTTP call within my successCallback function if the response data is null. I attempted to restart the process in the errorCallback, but due to the response.status always being 200, the error function never gets executed. Any suggestions on how to handle this scenario?

Answer №1

What do you think of this snippet?

The $q.reject function allows you to reject the current promise. When a promise is rejected, the 'then' method's callback stops executing and a catch callback is triggered.

var isValidLayer = $http({
   // ...
}).then(function(response) {
    if (response.status == 200 && response.data) {
        // ...
    } else if (response.data == null) {
        return $q.reject(response);
    } else {
       console.log(response.status)
    }
}).catch(function(errResponse) {
    console.log(errResponse);
});

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

The disappearance of ngx-charts lines is observed when the chart is rendered within a PrimeNG dialog that gets closed and reopened

In my TypeScript Angular application, I am currently incorporating PrimeNG. Specifically, I am utilizing the dialog component from PrimeNG to display charts using ngx-charts, specifically the ngx-charts-line-chart module. Initially, when I open the dialo ...

Implementing React hooks to efficiently remove multiple items from an array and update the state

Looking for help on deleting multiple items from an array and updating the state. I have selected multiple items using checkboxes, which are [5, 4, 3]. My goal is to remove all these items from the array based on their ids and then update the state accordi ...

A guide on displaying varying values of a single item across different dates in react.js

Here is an example of an array: array = [ { "id": 1, "date": { "id": 1, "name": "202001" }, "item": { "id": 1, "name": "I1" ...

How to toggle between two background colors in a webpage with the click of a button using JavaScript

I need help with a unique website feature. I want to implement a button that cycles between two different background colors (white and black) as well as changes the font color from black to white, and vice versa. My goal is to create a negative version of ...

Posts are not appearing on my WordPress theme

I'm currently facing an issue with applying a Wordpress theme to my website. Despite my attempts to fix it, I have been unsuccessful in getting it to work properly. The specific theme I am trying to use can be found on Github at this link. However, u ...

Is it possible to alter the canvas origin when using an Orthographic camera with a CSS3D

When transitioning the camera from perspective to orthographic, I noticed that the camera's position also shifts so that the coordinates 0,0,0 are situated in the top left corner. Is this expected behavior? Check out this Example for reference. Ortho ...

Tips on creating several conditions within a single filter

Currently, I am developing a filter system that is based on checkboxes. However, I am facing an issue where the JavaScript seems to ignore other conditions within the filter function when one condition is active. filterData() { return this.airlines.fil ...

Is it possible to implement jQuery events on all elements belonging to a specific class

Hey there, I'm facing a little challenge with my code. Currently, I have a snippet that allows a user using iOS to drag around a <div> with the class .drag on the webpage. Everything works perfectly when there's only one instance of .drag, ...

Display a modal immediately after a successful login to the page

Register form (separate file): <div class="" id="register-form"> <img class="Rpic" src="img/registerpic.png"> <div class="fieldtext"> <h2 class="text-center">Register</h2> </div> <div> <?php ...

Using Vue to turn a string into a mathematical operation

I'm in the process of creating a basic calculator using Vue, but I'm stuck on how to convert a string into a mathematical operation. I've already written the code for building the strings. <template> <div> <input type=&q ...

Error: Discord.js was unable to access the 'id' property because it was undefined

I need help with my ticket system project where I am trying to create a channel and send an embed in that channel. However, when I run the code, I encounter the error message TypeError Cannot read property 'id' of undefined. Here is the snippet ...

Checking if arrays are empty using ES6 conditional if statements

My JSX ES6 React if statement doesn't seem to be working. What could be the issue? const otherVariables = somethingElse; return ( ... <div> {if (props.student.length === null && props.teacher.length === null) => ( <p&g ...

Error: The current component does not have a template or render function specified. Check the <App>

I am a beginner in Vue js and I am facing an issue while running my application. It is showing an empty page with the error message: Component is missing template or render function. at <App>. Additionally, there is also a warning from Vue Router sa ...

Ensure that all input fields are validated simultaneously using the required attribute

I have been designing a form with various fields including text, number, and textarea. My goal is: I want to create a validation system for the form that checks all input fields with the required attribute in one single condition. For example, if the inp ...

Do you know of a solution to fix the Stylelint error regarding semicolons when using CSS variables?

React.js Css in JS(Emotion) The components above are part of this setup. Here is the configuration for Stylelint: module.exports = { extends: [ "stylelint-config-standard", "./node_modules/prettier-stylelint/config.js", ], ...

Is there a way to send a single POST request to two different external URLs simultaneously?

We recently encountered a limitation with one of our SaaS providers who only allows a single URL to be entered in the webhook field. However, we need this webhook request to be sent to two different analytics services simultaneously. To tackle this issue, ...

The code runs perfectly everywhere except inside a setTimeout function

I am currently utilizing light JS/jQuery automation to simplify repetitive tasks on a web application through Chrome. I have three setTimeout functions set up in such a way that they do not overlap. The first two are working correctly, but the third one ex ...

Is there a way to delete both the item and its corresponding key from localStorage?

I have developed a basic application that utilizes localStorage for saving and deleting data. However, I encountered an issue where deleting an item only removes the value but not the key. As a result, when loading all items, the deleted ones appear as nul ...

I'm experiencing an issue with the display of my Pop Up Window

I'm currently working on a website redesign project just for fun. One issue I've encountered is with a pop-up window that appears after clicking a button. Unfortunately, the layout of the window and button is quite strange - the button is positio ...

What steps can be taken to avoid caching PHP variables?

My code in functions.php on WordPress generates an affiliate link based on the visitor's location. It works perfectly, but there's a problem with page caching (W3 Total Cache). The variables get cached, so if a visitor from the UK opens the page ...