Search code examples
angularjsdependency-injectionangularjs-service

Is it considered a bad practice to request data from the server in a service constructor in Angular?


I have an angular service that is responsible for representing a collection of employees (that happens to be stored on the database normally). I hear that it is bad code smell to do a $http.get request inside the service's class's constructor. What I have been told is that I am supposed to inject the dependency that allows you to collect the relevant data but isn't that what I'm doing by using $http, using dependency injection?

So is it bad form to simply do var employees = $http.get('employees') from the server?

Many thanks!


Solution

  • Service is your model, all call to your server should be centralized in services.

    If i start from your example you should have an "EmployeeService" And in it a function like that : (don't forget to inject $q and $http services)

    me = this;
    me.cacheEmployee = null;
    me.getEmployees = function(){
        var deferred = $q.defer();
        if(me.cacheEmployee != null){
            deferred.resolve(me.cacheEmployee);
        }else{
           $http.get('urlToEmployee').success(function(result){
               me.cacheEmployee = result;
               deferred.resolve(me.cacheEmployee);
           });
        }
    
        return deferred.promise;
    };
    me.forceLoadEmployee = function(){ // after each CreateUpdateDelete operations
        var deferred = $q.defer();
        $http.get('urlToEmployee').success(function(result){
            me.cacheEmployee = result;
            deferred.resolve(me.cacheEmployee);
        });
        return deferred.promise;
    };
    

    And in the controller of the page you want to display your employees (don't forget to inject EmployeeService)

    EmployeeService.getEmployees().then(function(result){
       $scope.employees = result;
    });
    

    You use asynchronous call, you can't think in procedural way to resolve your problem.

    A basic doc about promise : https://docs.angularjs.org/api/ng/service/$q

    I hope my answer will fit you.

    Have a nice day !

    Edit : now you have a list of employee in cache, the call will be launched to the server only the first time.