$ HTTP承诺即使服务返回404,也会执行成功块



我感到困惑或可能不了解角度承诺的工作原理。我正在尝试为错误处理编写一些代码块,但我看到它总是在控制器中执行成功块。但是,我的服务也写了成功和错误块,因为我的响应需要进行一些转换。我看到它正在执行服务中的错误块,这很好,但同样的承诺在我的控制器中执行成功块。

html

<div ng-app="myApp">
    <div ng-controller="MainController">
         <h1>{{data}}</h1>
    </div>
<div>

JS

angular.module('services', []).service('myService', function($http) {
   this.getData = function() {
    return $http.get('test.json').then(function (response) {
        console.log(response);
        return response.data;
      },function(data) {
       console.log("Error block of service");
      });
   }
});

var app = angular.module('myApp', ['services']);
app.controller('MainController', ['$scope', 'myService', function ($scope, myService) {
    // Call the getData and set the response "data" in your scope.  
    myService.getData().then(function(myReponseData) {
        console.log("Success block of controller");
        $scope.data = myReponseData;
    },function(data) {
        console.log("Error block of controller");
        $scope.data = "Error " + data;
    });
}]);

我在小提琴中复制了相同的问题。看看jsfiddle

,因为这是Promise设计的方式。

如果您返回catch块内部的任何内容,则无论您返回什么都将成为链中的下一个链接的success

唯一的两种方式是:

  1. 恢复捕获的内部错误
  2. 返回您的捕获内部的拒绝承诺

这是一个更简单的示例:

Promise.reject(5)
  .catch(x => x * 2)
  .catch(err => console.log("THIS NEVER FIRES"))
  .then(x => console.log("Value is: ", x));
  // => "Value is: 10"
Promise.reject(5)
  .catch(x => Promise.reject(x * 2))
  .then(x => console.log("THIS NEVER FIRES"))
  .catch(err => console.log("Error is:", err));
  // => "Error is: 10"

在拒绝处理者中,重要的是重新犯错误。 否则,被拒绝的承诺将为转换为成功的承诺:

angular.module('services', []).service('myService', function($http) {
   this.getData = function() {
    return $http.get('test.json').then(function (response) {
        console.log(response);
        return response.data;
      },function(errorResponse) {
        console.log("Error block of service");
        //IMPORTANT re-throw error 
        throw errorResponse;
      });
   }
});

有关更多信息,请参见您缺少承诺的要点。

最新更新