2017-10-14 45 views
1

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

如果服务调用失败,代码会进入工厂的Catch部分,但仍返回到控制器,以便达到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

这是因为捕捉异常,你实际上吞咽。你或者不需要在你的工厂发现错误,或者重新抛出这样的错误:

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 
       }); 
     }, 
    }; 
}); 
+0

谢谢。您的解决方案都可以工 – chichi

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); 
       }); 
     };  
    }); 
+0

我已经尝试过这之前(或类似的东西)。我会再试一次,因为我认为这将是一个很好的解决方案。 – chichi

+0

@chichi告诉我你收到了什么错误? –