繁体   English   中英

如何检测Angular应用程序是否已从Angular外部初始化?

[英]How can I detect if an Angular app has been initialized from outside Angular?

在开发电梯-ng的插件,我注意到一个问题 :有时服务器通过彗星发送事件之前角初始化客户端。 这会导致应用程序无意中错过事件。 我想知道是否有办法检测应用程序是否已初始化,即所有控制器,服务,指令等都已实例化,因此所有监听器都已为事件做好准备。 因为这是一个插件,我需要能够做到这一点而不需要角度组件来实现任何代码。 我可以向应用程序添加控制器,服务或其他内容,但解决方案不能要求每个组件都发送一个事件。

尝试这样的事情:

try {
    angular.bootstrap(document)
} 
catch(e) {
    console.log(!!e.message.indexOf('btstrpd')) 
    //will log true if the error is of the type `btstrpd`, 
    //you can do whatever you want with it here.
}

如果已经有一个app bootstrap, angular.bootstrap将发出错误。 btstrpd是错误的名称,表示应用程序已经被引导。

这很简单,我希望它适用于你的情况,但是如果它没有ping我,我会想到更精细的东西。


另一种方法:

如果您有关于模块的一些信息,可以使用以下方法检查组件是否已经过引导:

angular.element(document.querySelector('[ng-app]')).injector().has('$http')

这个发现其中ng-app中使用属性,然后调用初始化喷油器的实例,从中你可以叫has看到什么提供商已被初始化。


另一种方法:

您可以尝试使用angular.module而不使用第二个参数,而不是angular.bootstrap ,如果模块已加载或发出错误,则应检索模块。

try {
    angular.module('moduleName')
} 
catch(e) {
    console.log(!!e.message.indexOf('nomod')) 
    //will log true if the error is of the type `nomod`, 
    //you can do whatever you want with it here.
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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