【问题标题】:$http.get to handle two different calls [duplicate]$http.get 处理两个不同的调用[重复]
【发布时间】:2019-12-01 20:53:36
【问题描述】:

我正在尝试使用 $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 不是函数

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

我该如何处理。

【问题讨论】:

  • 错字:.sucess 不是.success
  • .success 在 1.3 之前有效,如果你的 Angular js 版本高于 1.3,请使用 then()
  • @NagaSaiA 我尝试使用 .then 但我不确定如何检查呼叫是否成功,以便我可以呼叫另一个端点。你能告诉我如何使用 .then
  • @Amy 谢谢。但即使成功,我也会遇到同样的错误。
  • 我不希望修复一个缺陷来解决代码中的所有缺陷,尤其是 400 BAD REQUEST。

标签: javascript angularjs angularjs-http


【解决方案1】:

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

或者你可以使用承诺

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

            }
      });
};

【讨论】:

  • 我可以在errorCallback()中再次调用$http.get吗?
  • 是的,你可以做到
  • 没有帮助。我不让它工作
  • 我找到了一篇关于 angularjs http 服务和承诺的好文章。一旦你有时间通过​​它weblog.west-wind.com/posts/2014/Oct/24/…
  • 仍然出现同样的错误?
【解决方案2】:

为了实现预期的使用下面的选项,使用 $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

【讨论】:

  • 如果在无效的 URL 调用下没有注释 `$scope.myWelcome = response.data;` 是否仍然有效?
  • 不,它不会执行,因为它是无效的,并且会移动到错误处理部分并进行另一个调用,只是为了例如我使用它并评论的目的
  • 我添加了控制台供您参考,它只会看到错误控制台而不是控制台日志 - “成功第一次调用”,因为它失败了
  • 是的,第一次调用并不总是会失败,我的问题是如果第一次调用成功我需要重新获取数据。如果没有,则转到其他呼叫。如果我有 $scope.myWelcome = response.data; 它就存在了
  • 如果成功,它将使用 response.data 更新 $scope.main(我已经修改以区分),在使用 response.data 更新之前,使用一些默认值初始化 $acope.main,例如空字符串,null 可用时显示它
猜你喜欢
  • 1970-01-01
  • 2021-01-06
  • 2017-11-22
  • 1970-01-01
  • 2018-03-11
  • 1970-01-01
  • 1970-01-01
  • 2019-04-24
  • 1970-01-01
相关资源
最近更新 更多