0

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

georgeawg
  • 48,608
  • 13
  • 72
  • 95
trx
  • 2,077
  • 9
  • 48
  • 97
  • 2
    Typo: `.sucess` is not `.success`. –  Jul 23 '19 at 18:49
  • 1
    .success is valid till 1.3 , use then() if you angular js version is above 1.3 – Naga Sai A Jul 23 '19 at 18:49
  • @NagaSaiA I tried using .then but I am not sure how to check if the call is successful or not so I can call the other endpoint. Can you show me how I can do with .then – trx Jul 23 '19 at 18:52
  • @Amy Thanks. But even with success I get the same error. – trx Jul 23 '19 at 18:54
  • I wouldn't expect fixing that one defect to resolve all of the defects in your code, particularly the 400 BAD REQUEST. –  Jul 23 '19 at 18:56
  • @Amy I understand since it is a bad request I want to look if it is success or not and jump to the other end point. – trx Jul 23 '19 at 18:58
  • $http.get(url, config) .then((response) => console.log("response"), (error) => console.log("error")); – Naga Sai A Jul 23 '19 at 19:00
  • try to test with console.logs to debug – Naga Sai A Jul 23 '19 at 19:01
  • @NagaSaiA I can see the error in the logs, how can I adapt this to my scenario. I am new to javascripting any help is appreciated – trx Jul 23 '19 at 19:09
  • @trx, posted answer handling second API on error – Naga Sai A Jul 23 '19 at 19:14

2 Answers2

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

Naga Sai A
  • 10,771
  • 1
  • 21
  • 40
  • Does it still work if you have the ` $scope.myWelcome = response.data;` not commented under the invalid URL call? – trx Jul 23 '19 at 19:49
  • no it will not execute as it is invalid and will move to error handling part and makes another call, just for example purpose I used it and commented – Naga Sai A Jul 23 '19 at 19:52
  • I have added console just for your reference , and it will see only error console and not the console log - "success first call", as it got failed – Naga Sai A Jul 23 '19 at 19:54
  • Yeah It is not always the first call will fail, my problem is if the first call is successful I need to reterive the data . If not then move to other call. If I have the `$scope.myWelcome = response.data;` it just exists out – trx Jul 23 '19 at 20:09
  • if it is sucessful, it will update $scope.main(which i have modified to differentiate) with response.data , before updating with response.data, initialize $acope.main with some default value like empty string, null to show it when it is available – Naga Sai A Jul 23 '19 at 20:16
  • Did you update? – trx Jul 23 '19 at 20:25
  • @trx, updated with initial value for $scope.main and for testing give valid url for first call – Naga Sai A Jul 23 '19 at 20:28
  • Appreciate your help. Thanks – trx Jul 23 '19 at 20:46
-1

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() {

            }
      });
};
Syam
  • 303
  • 1
  • 8