Angular 2进样器层次结构和NgModule [英] Angular 2 injector hierarchy and NgModule

查看:70
本文介绍了Angular 2进样器层次结构和NgModule的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道NgModule实际上如何影响Angular 2喷射器层次结构.

I wonder how NgModule actually affects Angular 2 injector hierarchy.

在具有嵌套模块的应用程序中,层次结构是什么样的?它是为每个模块创建一个新的注入器实例,还是可以访问顶级注入器(类似于Angular 1.x模块)?

What does the hierarchy look like in an app with nested modules? Does it create a new injector instance per each module or gets access to top-level injector (similarly to Angular 1.x modules)?

在大型应用程序中找出树可能会有些混乱.

It can be somewhat confusing to figure out the tree in a big app.

是否有一种方法可以打印出,检查或直观地查看喷射器的层次结构(就像可以在Angular 1.x中实现作用域层次结构一样)?

Is there a way to print out, inspect or explore visually the hierarchy of injectors (like it could be done for scope hierarchy in Angular 1.x)?

推荐答案

根据模块文档: https://angular.io/docs/ts/latest/guide/ngmodule.html

Angular向模块执行上下文的根注入器注册这些提供程序.这是应用程序启动时加载的所有模块的应用程序的根注入器.

Angular registers these providers with the root injector of the module's execution context. That's the application's root injector for all modules loaded when the application starts.

Angular可以将这些提供程序服务之一注入任何组件中 在应用程序中.如果此模块提供了HeroService或其他 启动时加载的模块提供了HeroService,Angular可以注入 在任何应用程序组件中都使用相同的HeroService实例.

Angular can inject one of these provider services into any component in the application. If this module provides the HeroService, or any module loaded at launch provides the HeroService, Angular can inject the same HeroService intance into any app component.

延迟加载的模块具有其自己的子根注入器,通常 应用程序根注入器的直接子代.

A lazy loaded module has its own sub-root injector which typically is a direct child of the application root injector.

延迟加载的服务仅限于延迟模块的注入器.如果一个 延迟加载的模块还提供HeroService的任何组件 在该模块的上下文(例如,通过路由器导航)中创建的 服务的本地实例,而不是根目录中的实例 应用程序注入器.

Lazy loaded services are scoped to the lazy module's injector. If a lazy loaded module also provides the HeroService, any component created within that module's context (e.g., by router navigation) gets the local instance of the service, not the instance in the root application injector.

外部模块中的组件继续接收实例 为应用程序根目录创建的.

Components in external modules continue to receive the instance created for the application root.

因此,您有一个在所有模块之间共享的注射器.但是,延迟加载的组件将具有子注入器

So, you have one injector that is shared between all the modules. However, lazy-loaded components will have a child injector

这篇关于Angular 2进样器层次结构和NgModule的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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