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

查看:12
本文介绍了全局访问根 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天全站免登陆