全局访问根Angular 2注入器实例 [英] Accessing root Angular 2 injector instance globally

查看:125
本文介绍了全局访问根Angular 2注入器实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何全局访问根Angular 2注入器实例(例如,从浏览器控制台访问).

How to access an instance of root Angular 2 injector globally (say, from browser console).

在Angular 1中,它是angular.element(document).injector().

In Angular 1 it was angular.element(document).injector().

在测试和探索期间,使用浏览器控制台获取注入器然后访问不同组件,指令,服务等的实例可能很有用.

It can be useful during testing and exploration, to use browser console to get injector to then access instances of different components, directives, services etc.

推荐答案

启动应用程序后,必须将其设置为服务:

You must set it into a service after bootstrapping the application:

export var applicationInjector: Injector;

bootstrap([AppComponent]).then((componentRef: ComponentRef) => {
  applicationInjector = componentRef.injector;
});

然后,您可以将其导入应用程序的其他部分:

Then you can import it into other parts of your application:

import {applicationInjector} from './bootstrap';

有关更多详细信息,请参见此问题:

See this question for more details:

修改

您可以将ApplicationRef注入到组件中,并可以通过它访问根注入器:

You can inject the ApplicationRef into components and have access to the root injector through it:

@Component({
  (...)
})
export class SomeComponent {
  constructor(private app:ApplicationRef) {
    var rootInjector = app.injector;
  }
}

您需要利用依赖注入来获取它.

You need to leverage dependency injection to get it.

这篇关于全局访问根Angular 2注入器实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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