2
votes

I am trying to use Angular Service and since $scope can not be injected inside service so using $rootScope. My code look like fine but getting following error-

TypeError: $http.get is not a function

Here is code- EmployeeService.js: ///

app.factory('fetchEmpService', ['$rootScope', '$http', function ($http, $rootScope) {
    var employees = [];
    return {
        fetchEmp: function () {
            debugger;
            return $http.get("EmpWebService.asmx/GetEmp")
                .then(function (response) {
                    employees = response.data;
                    $rootScope.$broadcast('allEmployees', employees);
                    return employees;
                });
        }

    };
}]);

In my controller I am trying to consume it like below:

$scope.employees = fetchEmpService.fetchEmp();
$scope.$on('allEmployees', function (events, employees) {
        $scope.employees = employees;
    });

I am bit confuse that will the data will come inside $scope.$on

1
You have your parameters in the wrong order. $rootScope is injected first. Swap them around and it should be fine - Brendan Green
Change the answer in this line app.factory('fetchEmpService', ['$rootScope', '$http', function ($http, $rootScope). Here the injecting order is important. app.factory('fetchEmpService', ['$rootScope', '$http', function ($rootScope, $http) - Achu

1 Answers

10
votes

Your parameters and array of injectables are in a different order.

This:

app.factory('fetchEmpService', ['$rootScope', '$http', function ($http, $rootScope)

Needs to be

app.factory('fetchEmpService', ['$rootScope', '$http', function ($rootScope, $http)

The order is important and needs to be the same.

More information on dependency injection.