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.
At present I have a function in my controller which:
- Make an
$HTTP
call to an API - Processes the returned data with a
for
loop and aswitch
statement - Saves it to scope
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'.
Is there a more "Angular" way to achieve this, perhaps while using $q
?