如何动态实例化服务?

时间:2015-03-28 15:38:46

标签: angularjs dependency-injection angular-services objectinstantiation

我有Utils服务很重。我想在特定的用户操作中使用其中定义的一些功能。由于此服务很重,我想懒惰地实例化它(在用户操作上)。

我如何实现这一目标?

服务

module.service('Utils', function (dep1, dep2) {
   this.method1 = function () {
      // do something
   }
   // other methods
});

控制器

module.controller('AppCtrl', function ($scope) {
    // I don't want to inject Utils as a dependency.

    $scope.processUserAction = function () {
       // If the service is not instantiated 
       // instantiate it and trigger the methods defined in it. 
    }
});

标记

<div data-ng-controller="AppCtrl">
    <button data-ng-click="processUserAction()"> Click Me </button>
</div>

1 个答案:

答案 0 :(得分:1)

您可以使用$ injector服务在任何地方获取服务:https://docs.angularjs.org/api/auto/service/$injector。将$ injector注入控制器,并在需要服务时使用:

这对我来说很好,服务只在$ injector调用时实例化,没有抛出错误。

 angular.module('yp.admin')

    .config(['$stateProvider', '$urlRouterProvider', 'accessLevels', '$translateWtiPartialLoaderProvider',
        function ($stateProvider, $urlRouterProvider, accessLevels, $translateWtiPartialLoaderProvider) {
            $stateProvider
                .state('admin.home', {
                    url: "/home",
                    access: accessLevels.admin,
                    views: {
                        content: {
                            templateUrl: 'admin/home/home.html',
                            controller: 'AdminHomeController'
                        }
                    }
                });
        }])
    .service('UtilsService', function() {
        console.log('utilsSerivce instantiated');
        return {
            call: function() {
                console.log('Util.call called');
            }
        };
    })

    .controller('AdminHomeController', ['$scope', '$rootScope', 'UserService', '$injector',
        function($scope, $rootScope, UserService, $injector) {
        $injector.get('UtilsService').call();
    }]);    

控制台给了我这个:

stateChangeStart from:  to: admin.home
stateChangeSuccess from:  to: admin.home
utilsSerivce instantiated
Util.call called

如果您想延迟加载JS,请查看ocLazyLoad模块:https://github.com/ocombe/ocLazyLoad。它解决了各种延迟加载用例,你的听起来非常适合它。