gpt4 book ai didi

Angular:使用服务延迟加载模块

转载 作者:太空狗 更新时间:2023-10-29 17:06:08 25 4
gpt4 key购买 nike

我一直在关注 this教程,了解延迟加载,下面是我的推论。

场景 1:通过将服务放在子模块的 providers 数组中来提供服务

场景 2:使用 forRoot 方法在子模块中提供服务

在情景 1 中,

  • 如果预先加载子模块,则会将服务实例添加到根注入(inject)器。
  • 如果延迟加载子模块,则会将服务实例添加到根注入(inject)器,并将服务的新实例添加到子注入(inject)器,这不是通常的用例。

在情景 2 中,

  • 如果一个子模块被预先加载,服务的一个实例是添加到根注入(inject)器。

  • 如果一个子模块是延迟加载的,服务的同一个实例在根模块和子模块中都可用,这是通常用例。

他们提到了以下内容。

一开始,

So, even when using modules, there's no way to have a "private" service unless... the module is being lazy loaded.

最后,

Although this syntax is a little more convoluted than the original, it will guarantee us that only one instance of the CreditCardService is added to the root module. When the CreditCardModule is loaded (even lazy loaded), no new instance of that service is going to be added to the child injector.

如果该实例也将在根注入(inject)器中可用,他们怎么说该服务是“私有(private)化”的?

我很困惑。有人请澄清。

最佳答案

providedIn: 'root' 是自 Angular 6 以来最简单、最有效的服务提供方式:

  1. 该服务将作为单例在整个应用程序范围内可用,无需将其添加到模块的提供程序数组(如 Angular <= 5)。
  2. 如果该服务仅在延迟加载的模块中使用,它将与该模块一起延迟加载
  3. 如果从未使用过,它将不会包含在构建中(摇树)。

有关更多信息,请考虑阅读 documentationNgModule FAQs

顺便说一句:

  1. 如果您不想要应用程序范围的单例,请改用提供者的组件数组。
  2. 如果您想限制范围,使其他开发人员永远不会在特定模块之外使用您的服务,请改用提供者的 NgModule 数组。*

*更新

'use the provider's array of NgModule instead'表示使用延迟加载模块的providers数组,eg:

import { NgModule } from '@angular/core';

import { UserService } from './user.service';

@NgModule({
providers: [UserService],
})
export class UserModule {
}

或者在可注入(inject)装饰器中实际命名模块:

import { Injectable } from '@angular/core';
import { UserModule } from './user.module';

@Injectable({
providedIn: UserModule,
})
export class UserService {
}

引用自文档:

When the router creates a component within the lazy-loaded context,Angular prefers service instances created from these providers to theservice instances of the application root injector.

文档编号:https://angular.io/guide/providers#providedin-and-ngmodules

关于Angular:使用服务延迟加载模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48186872/

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