【发布时间】:2015-05-07 11:34:57
【问题描述】:
我想知道是否可以在多个级别上处理 ngResource 返回的$promise,以便代码是 DRY
这是一个简单的例子
aService = function(aResource) {
var error, success;
success = function(response) {
console.log('Service Success');
};
error = function(response) {
console.log('Service Error');
};
this.servicePostReq = function() {
return aResource.save().$promise.then(success, error);
};
return this;
angular.module('app.service').factory('aService', ['aResource', aService]);
到目前为止,这工作正常......当响应正常时它Service Success,当响应不正常时它Service Error
但是当我添加一个使用 aService 的控制器时,如下所示
aController = function(aService) {
var error, success;
success = function(response) {
console.log('Controller Success');
};
error = function(response) {
console.log('Controller Error');
};
this.controllerPostReq = function() {
aService.servicePostReq().then(success, error);
};
return this;
};
angular.module('app.controller').controller('aController', ['aService', aController]);
控制器总是成功...
所以如果请求返回成功输出是
Service Success
Controller Success
如果请求失败,输出是
Service Error
Controller Success
我如何链接承诺,这样我就不必为每个使用服务的控制器添加服务中处理的代码?
【问题讨论】:
标签: angularjs angularjs-service angularjs-controller angular-promise ngresource