-1

I am trying to call a function inside AngularJS service. Below is code- EmployeeService.js:

/// <reference path="script.js" />
app.factory('fetchEmpService', function ($scope, $http) {

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

    return {
        fetchEmp:fetchEmp,

    };

});

My main script file where I am calling service is-

  $scope.employees = fetchEmpService.fetchEmp();

It's not giving any error but no result is coming in it, seems it's returning blank. When I debugged by Browser Inspector I found that web service response is having data in Object form. So why it is not coming. Another question is, can we not inject $scope in AngularJS service factory?

br.julien
  • 3,420
  • 2
  • 23
  • 44
Ritesh Gupta
  • 171
  • 1
  • 2
  • 19
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Joe Clay Jun 01 '16 at 13:55

1 Answers1

0

You cannot return emplist from outside the then function. The then function is asynchronous and emplist will not be populated until after the http call is complete.

You may want to do something more like this:

app.factory('fetchEmpService', function ($scope, $http) {
  var service = this       

   service.fetchEmp: function() {
        var empList;
        return $http.get("EmpWebService.asmx/GetEmp")
            .then(function (response) {
                 empList = response.data;
                 return empList;
             });

   }

   return service

});

Then in your calling code do something like:

 fetchEmpService.fetchEmp.then( function(emplList) {
     // access the list here. 
 }
Mike Feltman
  • 5,160
  • 1
  • 17
  • 38