Mikos
Mikos

Reputation: 23

How repeat http call in AngularJS if response data is null and response status is 200

I am using a service that will send back XML with data in response. As a rule, everything works fine but sometimes the server incorrectly sends empty XML, without data.

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);
    });

How i can repeat http call inside my successCallback if response.data are null? I tried repeat this in errorCallback but response.status always is 200 and the error function is never execute.

Upvotes: 1

Views: 227

Answers (1)

Haegyun Jung
Haegyun Jung

Reputation: 755

How about this code?

$q.reject method is allow you to reject current promise. If promise is rejected, the callback of the 'then' method is stopped and a catch callback is executed.

var isokLayer = $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);
});

Upvotes: 1

Related Questions