[英]AngularJS, using a promise within a service
I have one of those "really fat controller" controllers from an MVP of a project, that I'd like to refactor into more modular and compartmentalised code. 我有一个来自项目MVP的“真正的胖控制器”控制器,我想将其重构为更具模块化和分隔性的代码。
At present I have a function in my controller which: 目前,我的控制器中具有以下功能:
$HTTP
call to an API 对API进行$HTTP
调用 for
loop and a switch
statement 使用for
循环和switch
语句处理返回的数据 I'd like to move this to a service. 我想将其转移到服务中。 So far I have this: 到目前为止,我有这个:
angular.module('myApp.services', [])
.service('apiService', ['$http', 'webapiBase', function($http, webapiBase) {
this.getData = function(){
$http.get(webapiBase + '/api/getData').then(function(res){
var obj = res.data;
// Processing stuff
return obj;
}, function(err){
return false;
})
}
}]);
In my controller, I need to run a callback when this service returns its data, like: 在我的控制器中,当此服务返回其数据时,我需要运行一个回调,例如:
// In my Service:
this.getData = function(cb){
$http.get(webapiBase + '/api/getData').then(function(res){
var obj = res.data;
cb(obj);
}, function(err){
cb(false);
})
}
// In my controller
apiService.getData(function(data){
$scope.data = data;
// Do other stuff here
})
But this feels a bit weird/non-'Angular'. 但这感觉有点奇怪/非“ Angular”。
Is there a more "Angular" way to achieve this, perhaps while using $q
? 有没有更多的“角度”方式来实现这一目标,也许在使用$q
?
You just need to make a small modification to your service 您只需要对服务进行一些小修改
this.getData = function(){
return $http.get(webapiBase + '/api/getData').then(function(res){
// Processing stuff
return object;
}, function(err){
return false;
})
}
Return the promise object of $http.get
directly. 直接返回$http.get
对象。 Then in your controller 然后在您的控制器中
apiService.getData().then(function(data){
$scope.data = data;
// Do other stuff here
})
If you really don't want to reuse the promise object created by $http
, you can create your own real quick. 如果您确实不想重复使用$http
创建的promise对象,则可以创建自己的real quick。
this.getData = function() {
var deferred = $q.defer();
$http.get(webapiBase + '/api/getData').then(function(res){
// Processing stuff
deferred.resolve(object);
}, function(err){
deferred.reject('error');
});
return deferred.promise;
}
You can use $q
to achieve what you're looking for. 您可以使用$q
来实现所需的功能。
// Your service
angular.module('myApp.services', [])
.service('apiService', ['$http', 'webapiBase', function($http, webapiBase) {
this.getData = function() {
var deferred = $q.defer();
$http.get(webapiBase + '/api/getData').then(
function (res) {
// Do something with res.data
deferred.resolve(res.data);
},
function(res){
deferred.reject();
}
);
return deferred.promise;
}
}]);
Then consume the $q
promise in your controller and respond to it: 然后在控制器中使用$q
promise并对其作出响应:
// Your controller
apiService.getData().then(function(data) {
$scope.data = data;
// Do other stuff here
});
That's the Angular-way, using promises with $q
. 这就是Angular方式,在$q
使用promises。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.