gpt4 book ai didi

javascript - 中间模块提供者如何融入注入(inject)器树

转载 作者:太空宇宙 更新时间:2023-11-04 16:20:12 24 4
gpt4 key购买 nike

This tutorial除了这句话之外,没有过多讨论模块如何适合注入(inject)器树:

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

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

最佳答案

我认为您正在寻找 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 从依赖于其父级及其父级父级的组件中查找,...对于提供者,最后在应用程序的根范围内或在延迟加载模块的根范围内(如果该组件是其中的一部分) .

关于javascript - 中间模块提供者如何融入注入(inject)器树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40714574/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com