I have this service to retrieve a list of cars from a WebAPI server :
angular.module('MyServices')
.service('carService', ['$http', '$rootScope',
function ($http, $rootScope) {
this.getList =function(userName, ticket)
{
$rootScope.$emit('My.OnBusy');
$http.get('api/car'
, { params: {userName: userName} }
).success(function (data) {
$rootScope.$emit('My.OnIdle');
if (data[0] && data[0].Name == "Error")
{
$rootScope.$emit("My.OnError", data[0].Model);
return {};
}
return data;
}).error(function (data, status, headers, config) {
$rootScope.$emit('My.OnIdle');
$rootScope.$emit("My.OnError", "Error in communication with server.");
return {};
});
}
}]
);
And in the controller I use it like this :
angular.module('MyControllers')
.controller('carController', function CarController($rootScope, $scope, $http, carService) {
$scope.loadCars = function (userName, ticket) {
$scope.Cars = carService.getList(userName, ticket);
}
$scope.loadCars($rootScope.user.email, '');
});
But the $scope.Cars is Undefined after the cal to getList. I tried to use "then" when I call the service but it was unsuccessful.
Saying that I want to handle success and error of the operation in the service itself, how can I get final result in the controller?
For future reference :
Service should be like this :
angular.module('MyServices')
.service('carService', ['$http', '$rootScope', '$q'
function ($http, $rootScope, $q) {
this.getList =function(userName, ticket)
{
$rootScope.$emit('My.OnBusy');
var deferred = $q.defer();
$http.get('api/car'
, { params: {userName: userName} }
).success(function (data) {
$rootScope.$emit('My.OnIdle');
if (data[0] && data[0].Name == "Error")
{
$rootScope.$emit("My.OnError", data[0].Model);
deferred.reject(data[0].Address);
//return {};
}
deferred.resolve(data);
//return data;
}).error(function (data, status, headers, config) {
$rootScope.$emit('My.OnIdle');
$rootScope.$emit("My.OnError", "Error in communication with server.");
deferred.reject("Error in communication with server.");
//return {};
});
return deferred.promise;
}
}]
);
And now "then" works in the controller :
angular.module('MyControllers')
.controller('carController', function CarController($rootScope, $scope, $http, carService) {
$scope.loadCars = function (userName, ticket) {
carService.getList(userName, ticket).then(function (data) {
$scope.Cars = data;
});;
}
$scope.loadCars($rootScope.user.email, '');
});