在AngularJS中实例化全局服务 [英] Instantiate global services in AngularJS

查看:69
本文介绍了在AngularJS中实例化全局服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用AngularJS开发一个新的系统.该应用程序当前具有许多控制器,服务和指令以及许多依赖项.

该系统大约有9个服务,并且大多数服务都在多个控制器中重用,因此我将它们注入到父控制器中,以便子控制器可以访问它们.每个服务都存储整个系统中使用的数据.

但是,随着开发的进行,我发现它变得越来越难管理,并且在某些情况下,我必须做一些修改才能在不同的地方使用服务实例./p>

我的问题是,不是将所有服务注入到主控制器中,而是应该将它们作为全局变量实例化在app.js文件中...但是我真的不喜欢具有全局变量的想法,所以除了这样做,还有其他解决方案吗?

解决方案

服务是Angular中的单例,因此您应该将其注入所需的任何位置.不必将它们注入祖先并将其传播下去.只需将其直接注入孩子体内即可.无论如何,只有一个服务实例,为什么不那样做就更简单呢?

I am currently developing a new system at work, using AngularJS. And the application currently has many Controllers, Services and Directives, and many dependencies.

The system has about 9 services, and most of them are reused in multiple controllers, so I injected them into the parent controller so they can be accessible by children controllers. Each service stores data used throughout the whole system.

However, as the development progresses, I find that it is getting harder and harder to manage, and in some cases, I have to do a bit of hack to be able to use the instance of a service at different places.

My question here is, instead of injecting all services into the main controller, should I instead instantiate them in the app.js file as global variables... but I don't really like the idea of having global variables, so besides doing this, would there be any alternative solution to this?

解决方案

Services are singletons in Angular, so you should just inject them where ever you need them. It's not necessary to inject them in to an ancestor and propegate it down. Just inject it directly into the child as well. There is only one instance of the service regardless, so why not just make it easier that way?

这篇关于在AngularJS中实例化全局服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆