gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 11:17:45 26 4
gpt4 key购买 nike

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/

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