问题描述
在我的角度应用程序我有一个控制器。该控制器具有一个名为服务
服务调用异步函数的方法。这是控制器code:
In my angular app I have a controller. The controller has a method which calls an asynchronous function in a service called Service
. This is the controller code:
$scope.controllerMethod = function(){
Service.serviceMethod($scope.x, $scope.y).then(function(data){
//request succeeded, so do nothing
}, function(data){
//there was an error, show error message
});
}
和这是 serviceMethod
的服务
服务中的:
serviceMethod: function(x, y){
return $http.post('save', {
id: x, type: b
}).then(function(data){
//update variables in the service
}, function(data){
//send error message to controller
});
}
在该服务
方法调用服务器,服务器将在必要时返回一个错误。我如何可以发送错误响应我的控制?在当前的设置,不管在 $ HTTP
请求返回成功或错误,则在控制器延迟总是执行它的成功方法。我想调用在控制器的延迟误差的方法,把它传到服务器的数据。
When the Service
method calls the server, the server will return an error if necessary. How can I send that error response to my controller? With the current setup, no matter if the $http
request returns success or error, the deferred in the controller always executes it's success method. I want to invoke the error method for the deferred in the controller passing it the data from the server.
推荐答案
我会写的服务为:
serviceMethod: function(x, y){
return $http.post('save', {
id: x, type: b
}).success(function(data){
// do things Service related when call is successful
}).error(function(data, status){
// do things error related...
})
}
然后引用它在这样的控制器:
And then reference it in a controller like this:
Service.serviceMethod($scope.x, $scope.y).success(function(data){
// request succeeded, so do nothing
}).error(function(data, status){
// error occured, do whatever
});
这就像一个魅力...这里是
This works like a charm... Here is docs
这篇关于从服务角度传球推迟错误控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!