从服务角度传球推迟错误控制器 [英] Angular pass deferred error from service to controller

查看:137
本文介绍了从服务角度传球推迟错误控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的角度应用程序我有一个控制器。该控制器具有一个名为服务服务调用异步函数的方法。这是控制器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

这篇关于从服务角度传球推迟错误控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆