$http.get 处理两个不同的调用

$http.get to handle two different calls

我正在尝试使用 $http.get 调用端点并检查成功代码是否为 200 然后使用响应数据,否则我需要调用其他端点。我尝试检查调用是成功还是错误,如下所示,

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

我希望如果对 $scope.BaseURL 的调用失败,它将转到错误函数并调用 $scope.diffURLreturns 响应,但我得到的错误如下

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"}`

我该如何解决这个问题。

您可以使用 $http then 方法

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

或者你可以使用 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;
        });
}

您可以像这样使用您的第一个方法

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

            }
      });
};

为了实现以下选项的预期使用,使用 $http.get 链接 API 调用而不是成功,因为它用于 Angularjs 1.3 版和 1.3 以上版本使用。然后()

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

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

   }
   })

供参考的工作代码示例

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