Ritesh Gupta Ritesh Gupta - 5 months ago 24
AngularJS Question

Data retrieval works within a controller but not when I use a service - AngularJS

I am implementing some functionality to retrieve a list of employees from database to display within my AngularJS application. I created a controller that current works as displayed below:

$scope.getEmployee = function () {
$http.get("EmpWebService.asmx/GetEmp")
.then(function (response) {
$scope.employees = response.data;
});
}


I tried to move this logic to be used within a service but the data is returning
undefined
. It's strange because this was working fine few days ago but suddenly it does not appear to be working. Here is the code:

Controller

$scope.getEmployee2 = function () {
$scope.employees = fetchEmpService.fetchEmp();
}


Service.js

fetchEmp: function () {
debugger;
return $http.get("EmpWebService.asmx/GetEmp")
.then(function (response) {
return response.data;

});
}

Answer

The above code will not work because fetchEmp will return a promise so $scope.employees is a promise not the employee list, try to do this,

$scope.getEmployee2 = function () {
    fetchEmpService.fetchEmp().then(function (employeeList){
        $scope.employees = employeeList;
    });
}