我的控制器中有一些代码直接调用$http来获取数据.
现在我想将其转变为服务.这是我到目前为止:
现在我想将其转变为服务.这是我到目前为止:
我的服务:
angular.module('adminApp',[]) .factory('TestAccount',function ($http) { var TestAccount = {}; TestAccount.get = function (applicationId,callback) { $http({ method: 'GET',url: '/api/TestAccounts/GetSelect',params: { applicationId: applicationId } }).success(function (result) { callback(result); }); }; return TestAccount; });
控制器内部:
TestAccount.get(3,function (data) { $scope.testAccounts = data; })
我怎样才能改变这一点,而不是将成功的结果传回去
传回一个承诺,我可以检查它是否成功或失败?
解决方法
让您的服务返回承诺并将其公开给服务客户.像这样更改您的服务:
angular.module('adminApp',function ($http) { var TestAccount = {}; TestAccount.get = function (applicationId) { return $http({ method: 'GET',params: { applicationId: applicationId } }); }; return TestAccount; });
所以在控制器中你可以这样做:
TestAccount.get(3).then(function(result) { $scope.testAccounts = result.data; },function (result) { //error callback here... });