Ritesh Gupta Ritesh Gupta - 5 months ago 8
AngularJS Question

function works in controller but not in service in Angular Js

I am implementing functionality to get all list of employee from data base in Angular JS application. So I made a function in controller. Here it is-

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


And it is working fine. But I tried to make this in Service of Angular JS it is returning undefined, though it was working fine few days ago but suddenly not working. Here is code in service-
Calling from 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;
    });
}