Javascript 管理来自服务的成功和错误响应
在我的控制器上,我有大量的服务调用,因此每次收到响应时,我都在执行相同的操作,因此我想知道是否有方法统一每个服务调用的“成功”和“错误”功能,以便删除重复的代码 还有,如果有一种方法应该放在哪里Javascript 管理来自服务的成功和错误响应,javascript,angularjs,angular-services,Javascript,Angularjs,Angular Services,在我的控制器上,我有大量的服务调用,因此每次收到响应时,我都在执行相同的操作,因此我想知道是否有方法统一每个服务调用的“成功”和“错误”功能,以便删除重复的代码 还有,如果有一种方法应该放在哪里 this.UpdateProfile = function (profile) { profilePageDataService.UpdateProfile(profile) .success(
this.UpdateProfile = function (profile) {
profilePageDataService.UpdateProfile(profile)
.success(
function (data, status) {
alert('Yeah');
})
.error(
function (data, status) {
alert('Ko');
});
};
编辑:
所以我想澄清一下,我只想去掉“成功与错误”,因为里面的代码是一样的
this.UpdateProfileName = function (profile) {
profilePageDataService.UpdateProfileName(profile)
.success(
function (data, status) {
alert('Yeah');
})
.error(
function (data, status) {
alert('Ko');
});
};
您可以向服务函数添加回调
this.UpdateProfile = function (profile, callback) {
var cb = callback || angular.noop; // just a safer way. do nothing in you did not specify `callback` variable.
profilePageDataService.UpdateProfile(profile)
.success(
function (data, status) {
return cb(data);
})
.error(
function (data, status) {
return cb(data);
});
};
要获取回调,请执行以下操作:
var userProfile = {};
MyService.UpdateProfile(userProfile, function(response) {
console.log(response);
});
在$rootScope中移动您的
UpdateProfile
函数如何:
angular.module('scopeExample', [])
.controller('RootController', ['$scope', '$rootScope', 'profilePageDataService', function($scope, $rootScope, profilePageDataService) {
$rootScope.UpdateProfile = function (profile) {
profilePageDataService.UpdateProfile(profile)
.success(
function (data, status) {
//Some operations here...
})
.error(
function (data, status) {
//.....
});
};
}])
.controller('ProfileController', ['$scope', function($scope) {
//UpdateProfile function moved from here to $rootScope
}]);
我认为上面的代码可以工作(注意,我还没有测试它),但是上面的代码是按照示例实现的
在这种情况下,还有另一种选择可能也适用,它涉及使用