gpt4 book ai didi

angularjs - 我怎样才能传回从AngularJS服务 promise ?

转载 作者:行者123 更新时间:2023-12-01 02:26:25 25 4
gpt4 key购买 nike

我的 Controller 中有一些代码直接调用 $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;
});

Controller 内部:
   TestAccount.get(3, function (data) {
$scope.testAccounts = data;
})

我怎样才能改变这一点,而不是将成功的结果传回它
传回一个我可以检查它是成功还是失败的 promise ?

最佳答案

使您的服务返回 promise 并将其公开给服务客户。像这样改变你的服务:

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;
});

所以在 Controller 中你可以这样做:
TestAccount.get(3).then(function(result) {
$scope.testAccounts = result.data;
}, function (result) {
//error callback here...
});

关于angularjs - 我怎样才能传回从AngularJS服务 promise ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16001400/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com