$http.get to handle two different calls

All we need is an easy explanation of the problem, so here it is.

I am trying to call a endpoint using $http.get and check if the succsess code is 200 then use the response data otherwise I need to call other endpoint. I tried to check if the call is success or error like below,

    $scope.getRequest = function () {
        var url = $rootScope.BaseURL;
        var config = {
            headers: {
                'Authorization': `Basic ${$scope.key}`,
                'Prefer': 'odata.maxpagesize=10000'
            }
        };
        $http.get(url, config)
            .success(
            function (response) { // success async
                $scope.viewRequest.data = response.data;
            })
            .error(function (response) { // failure async
                var url = $rootScope.diffURL;
                $http.get(url, config)
                    .success(
                    function (response) { // success async
                        $scope.viewRequest.data = response.data;
                    })
                    .error(function (response) { // failure async
                        console.log("There was an error getting the request from CORE");
                    });
            });
    };

I was hoping if the call to $scope.BaseURL fails it will go to the error function and calls the $scope.diffURLreturns the response but I am getting below errors

angular.js:14800 TypeError: $http.get(…).success is not a function

GET https:\\example.com\... 400 (Bad Request)

Possibly unhandled rejection: {"data":{"error":{"code":"1001","message":"
The property, used in a query expression, is not defined in type ‘T’.”}},”status”:400,”config”:{“method”:”GET”,”transformRequest”:[null],”transformResponse”:[null],”jsonpCallbackParam”:”callback”,”headers”:{“Authorization”:”Basic 0h”,”Prefer”:”odata.maxpagesize=10000″,”Accept”:”application/json, text/plain, /“},”url”:”https://example.com...,”statusText”:”Bad Request”,”xhrStatus”:”complete”}`

How can I approach this.
enter image description here

How to solve :

I know you bored from this bug, So we are here to help you! Take a deep breath and look at the explanation of your problem. We have many solutions to this problem, But we recommend you to use the first method because it is tested & true method that will 100% work for you.

Method 1

To achieve expected use below option of chaining API calls with $http.get with then instead of success ,as it is used to Angularjs version 1.3 and from above 1.3 use .then()

$http.get('<url>')  // Replace url, url2 with actual urls
   .then(function(response){

   }, function(error){
     $http.get('<url2>')
   .then(function(response2){
      // Handle response
   }, function(error2){

   }
   })

working code sample for reference

var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$scope.main= '';
  $http.get("https://output.jsbin.com/http-promise-chain-json/14.json") //Invalid URL
  .then(function(response) {
console.log("success first call")
     $scope.main= response.data;
  }, function(error){
console.log("error")
    $http.get("https://output.jsbin.com/http-promise-chain-json/1.json")
  .then(function(response) {
      $scope.myWelcome = response.data;
  }, function(error) {
      
  })
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="myCtrl"> 

<h1>{{myWelcome}}</h1>
<h1>{{main}}</h1>

</div>

<script>

</script>

</body>

codepen – https://codepen.io/nagasai/pen/jgOgmV

Method 2

You can use $http then method

$http({
  method: 'GET',
  url: '/someUrl'
}).then(function successCallback(response) {
    // this callback will be called asynchronously
    // when the response is available
  }, function errorCallback(response) {
    // called asynchronously if an error occurs
    // or server returns response with an error status.
  });

Or You can use promises

function getRequest1(url) {  // This will return a promise object, also you can reuse this method for make subsequent request
    return $http.get(url)
        .success(function(data) {
            return data;
        });
}

You can consume your first method like this

var getRequest2 = function() {
      let url1 = "first url";
      getRequest1(url1)
      .success(function(data) {            
          //If the "getRequest1()" method is success you will get the result here
          console.log("Data from success function of getRequest1()", data);
      })
      .error(function() {
         // If getRequest1() method fail you can call fallback url from here
         var url2 = "second url";
         getRequest1(url2)
            .success(function(data) {            
              //If the "getRequest1()" method is success you will get the result here
              console.log("Data from success function of getRequest1()", data);
            })
            .error(function() {

            }
      });
};

Note: Use and implement method 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply