中间模块提供者如何适应注入器树

How does intermediary module providers fit into injector tree

This tutorial 没有过多谈论模块如何适应注入器树,除了这个短语:

All requests bubble up to the root NgModule injector that we configured with the bootstrapModule method.

这是否意味着如果在树上的任何组件上都找不到提供程序,则只检查根模块而不检查其他中间模块?例如,下图显示了具有一个根组件的组件树,组件 3 和 4 在它自己的模块中声明。根模块有自己的提供者,红色模块有自己的提供者。当组件 3 请求服务时,是否忽略红色模块上的提供者并检查父组件上的提供者,如果找不到则返回根模块上的提供者?

我想你正在寻找 https://angular.io/docs/ts/latest/cookbook/ngmodule-faq.html#!#q-module-provider-visibility

Why is a service provided in a feature module visible everywhere? Providers listed in the @NgModule.providers of a bootstrapped module have application scope. Adding a service provider to @NgModule.providers effectively publishes the service to the entire application.

When we import a module, Angular adds the module's service providers (the contents of its providers list) to the application root injector.

This makes the provider visible to every class in the application that knows the provider's lookup token.

This is by design. Extensibility through module imports is a primary goal of the Angular module system. Merging module providers into the application injector makes it easy for a module library to enrich the entire application with new services. By adding the HttpModule once, every application component can make http requests.

However, this can feel like an unwelcome surprise if you are expecting the module's services to be visible only to the components declared by that feature module. If the HeroModule provides the HeroService and the root AppModule imports HeroModule, any class that knows the HeroService type can inject that service, not just the classes declared in the HeroModule.

模块的提供者被添加到根范围。重复项被丢弃。这意味着提供程序是从您的整个应用程序中找到的,除非它们在组件或延迟加载的模块上被覆盖。延迟加载的模块有自己的根作用域。

如果红色模块是延迟加载的,那么组件 3 将从该模块获取提供程序,如果它是急切加载,则红色模块的提供程序将添加到应用程序的根范围,组件 3 将从那里获取它.这都与 @NgModule()

添加的提供商有关

添加到 @Component()@Directive() 的提供程序不会提升到任何根范围。 DI 从依赖于其父级及其父级父级的组件中寻找提供者,最后在应用程序的根范围内查找,或者如果组件是其中的一部分,则在延迟加载模块的根范围内查找.