简体   繁体   中英

AngularjS Services/Factories loaded on startup and not on use

I have a problem with my AngularJS app. I have some factories defined which are injected into some controllers (where needed). My Problem is that these factories get initialized when I first startup the application.

One of the services which is causing problems:

PlanningPoker.factory('PokerTable', function ($http) {
var baseURL = "/api/pokertable/";

return {
    list: function list(playerId) {
        return $http.get(baseURL, {params: {playerid : playerId}});
    },
    save: function save(pokertable) {
        return $http.post(baseURL, pokertable, {});
    }
};

});

This service is used like this in a controller:

PlanningPoker.controller('PokerTableListController', function ($rootScope, $scope, $route, PokerTable, SocketEvent) {
PokerTable.list($rootScope.playerId).
    success(function (data, status, headers, config) {
        $scope.pokertables = data;
    });

});

Also when I remove the PokerTable Service from the controllers callback the Service gets called. I tried this by adding a console.log into the service and it was called no matter if the service was used in any controller or not.

Any ideas on that? I thought services are loaded lazily only if they are needed?

Greets Marc

Services are constructed or retrieved when they are injected by the injector to ensure dependencies work out. You can read about it here

Alternatively you can use the $injector service to grab services as needed. Here is an example:

    .controller('test', function($scope, $injector) {
      $scope.func = function() {
        var factory = $injector.get('factory');
      };
    });

http://jsfiddle.net/NaYmd/

You'll notice the alerts in the service are not called until you click the span, since that's when the injector causes the construction of the factory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM