angular - 延迟加载模块中的 Angular 组件是否获取全局服务的副本?

标签 angular angular-providers

Angular docs 我不确定我是否理解

Angular providers documentation状态:

When the Angular router lazy-loads a module, it creates a new injector. This injector is a child of the root application injector. Imagine a tree of injectors; there is a single root injector and then a child injector for each lazy loaded module. The router adds all of the providers from the root injector to the child injector. When the router creates a component within the lazy-loaded context, Angular prefers service instances created from these providers to the service instances of the application root injector.

Any component created within a lazy loaded module’s context, such as 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.

问题

这是否意味着当我在延迟加载模块中访问任何全局声明的提供程序时,我访问的是它的副本,它与在根注入(inject)器中创建的实例是分开的?

假设我有两种情况:

情况A

  • 根模块 AppModule
    • 提供 ProviderX
    • 声明 AppComponent
      • 注入(inject) ProviderX
  • 延迟加载模块 SubpageModule
    • 无供应商
    • 声明子页面组件
      • 注入(inject) ProviderX

情况B

  • 根模块 AppModule
    • 提供 ProviderX
    • 声明 AppComponent
      • 注入(inject) ProviderX
  • 延迟加载模块 SubpageModule
    • 提供 ProviderX
    • 声明子页面组件
      • 注入(inject) ProviderX

在情况 A 中,SubpageComponent 中的 ProviderX 实例与 AppComponent 中的实例相同还是不同?我知道在情况 B 中他们不是。

最佳答案

情况A

AppComponent 和 SubpageComponent 得到同一个实例注入(inject)

情况B

AppComponent 和 SubpageComponent 得到不同的实例注入(inject)

通过您的设置,您将获得一个注入(inject)器层次结构,如

- AppModule
 |- AppComponent
 |- SubPageModule
   |- SubpageComponent

Angular 从需要注入(inject)值的位置向上搜索树结构,直到找到第一个匹配的提供者。然后它注入(inject)第一个找到的提供者提供的实例。

关于angular - 延迟加载模块中的 Angular 组件是否获取全局服务的副本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48460165/

相关文章:

angular - 错误 :NullInjectorError: No provider for Router

asp.net - 在 ASP.Net MVC 中使用 @Html.AntiForgeryToken() 提供 CSRF token 的替代方法

angular - 设置值后不显示自动完成

javascript - Angular 4 忽略空字段的 HTML 显示

angular - 没有简单组件的提供者

angular - 延迟加载和提供者策略

javascript - 动态过滤字符串列表

html - 如何更改重叠按钮的 "click order"?

typescript - 从另一个模块导入服务