我怎样才能传回从AngularJS的服务的承诺? [英] How can I pass back a promise from a service in AngularJS?
本文介绍了我怎样才能传回从AngularJS的服务的承诺?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在控制器中的一些code被直接调用$ HTTP来获取数据。
现在我想这个移动到服务。以下是我迄今为止:
I have some code in my controller that was directly calling $http to get data. Now I would like to move this into a service. Here is what I have so far:
我的服务:
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;
})
我怎样才能改变这种做法,而不是传递成功的结果返回它
传回,我可以检查,看它是否成功或承诺失败了?
How can I change this so rather than passing the result of success back it passes back a promise that I can check to see if it succeeded or failed?
推荐答案
请您的服务来回报的承诺,并将其暴露给服务客户端。更改像这样的服务:
Make your service to return a promise and expose it to service clients. Change your service like so:
angular.module('adminApp', [])
.factory('TestAccount', function ($http) {
var TestAccount = {};
TestAccount.get = function (applicationId) {
return $http({
method: 'GET',
url: '/api/TestAccounts/GetSelect',
params: { applicationId: applicationId }
});
};
return TestAccount;
});
所以控制器可以这样做:
so in a controller you can do:
TestAccount.get(3).then(function(result) {
$scope.testAccounts = result.data;
}, function (result) {
//error callback here...
});
这篇关于我怎样才能传回从AngularJS的服务的承诺?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文