首页 > 解决方案 > $http.get 处理两个不同的调用

问题描述

我正在尝试使用 $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.diffURL返回响应,但我得到以下错误

angular.js:14800 TypeError: $http.get(...).success 不是函数

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

可能未处理的拒绝:{"data":{"error":{"code":"1001","message":" 在查询表达式中使用的属性未在类型 '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"}`

我该如何解决这个问题。 在此处输入图像描述

标签: javascriptangularjsangularjs-http

解决方案


为了实现下面的预期使用,使用 $http.get 链接 API 调用的选项,然后而不是成功,因为它用于 Angularjs 版本 1.3 并且从 1.3 以上使用 .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){

   }
   })

工作代码示例供参考

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


推荐阅读