【发布时间】:2015-03-28 15:38:45
【问题描述】:
我有一个很重的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>
【问题讨论】:
-
该服务的“重”是什么:JS 文件很大,所以您想延迟加载它吗?服务实例化需要很多时间,所以你想延迟它吗?它是一个大的“内存”对象,你想节省内存吗?根据答案,解决方案将非常不同。但我认为“不注入”它不会获得任何好处,因为只要将服务添加到模块中,加载和实例化就会完成,而且无论如何它都是单例。
-
服务/工厂的实例化只有在我们将它们作为依赖注入时才会发生。通过繁重的方式实例化服务需要一些时间。为了加快页面的加载速度,我想懒惰地实例化服务。
-
调整答案以显示 $injector 服务,这将解决您的问题
标签: angularjs dependency-injection angular-services objectinstantiation