如何防止对AngularJS中失败的$ http.post采取行动

时间:2017-10-14 10:27:43

标签: angularjs

在我的工厂,我打了一个服务电话。如果我从该调用中得到响应,我想在我的控制器中执行操作(即调用函数doAction())。 我需要一些帮助。由于我的代码现在正在运行,即使服务调用失败,它也会在控制器中执行操作。

如果服务调用失败,代码将进入工厂的Catch-section,但仍会返回到控制器,以便达到doAction() - 方法。

我该如何避免?感谢您的时间,并原谅一个可能的愚蠢问题。我对Angular很新。

在我的工厂:

app.factory('myFactory', function ($http) {
    return {

        callService: function () {
            return $http.post("http://xxxxx", {}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
                .then(function(response) {
                    return response.data;
                })
                .catch(function(response) {
                    console.error(response.status, response.data);
                });
        },
    };
});

在我的控制器中:

var app = angular.module('indexapp', ['ngRoute']);

app.controller('indexController', function($scope, myFactory) {

   $scope.makeServiceCall = function() {
        var data = myFactory.callService();
        data.then(function (result) {
            doSomeAction();
        });
    };    
});

2 个答案:

答案 0 :(得分:2)

从工厂服务返回promise

<强>工厂:

app.factory('myFactory', function ($http) {
    return {

        callService: function () {
            return $http.post("http://xxxxx", {}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}});                    

    };
});

<强>控制器

var app = angular.module('indexapp', ['ngRoute']);

    app.controller('indexController', function($scope, myFactory) {

       $scope.makeServiceCall = function() {
            var data;
            myFactory.callService().then(function(response) {
                    data = response.data;
                    doSomeAction();
                })
               .catch(function(response) {
                    console.error(response.status, response.data);
                });
        };    
    });

答案 1 :(得分:2)

这是因为通过捕获异常,您实际上是在吞咽它。您要么不需要在工厂中捕获错误,要么重新抛出错误:

app.factory('myFactory', function ($http) {
    return {

        callService: function () {
            return $http.post("http://xxxxx", {}, {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
                .then(function(response) {
                    return response.data;
                })
                .catch(function(response) {
                    console.error(response.status, response.data);
                    throw response; // <-- rethrow error
                });
        },
    };
});