简体   繁体   English

访问 Angular 懒加载模块中的根服务

[英]Access root services in Angular lazy loaded module

I am playing with Angular lazy loaded modules and want to access a root service say AuthService in lazy loaded modules.我正在使用 Angular 延迟加载模块,并希望在延迟加载模块中访问根服务说AuthService I want to access the singleton instance present in the root injector in the lazy loaded modules.我想访问延迟加载模块中根注入器中存在的 singleton 实例。

I am following https://angular.io/guide/providers and there are two statements causing the confusion:我正在关注https://angular.io/guide/providers并且有两个语句导致混淆:

When you add a service provider to the root application injector, it's available throughout the app.当您将服务提供者添加到根应用程序注入器时,它在整个应用程序中都可用。

When the Angular router lazy-loads a module, it creates a new injector.当 Angular 路由器延迟加载模块时,它会创建一个新的注入器。 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.当路由器在延迟加载上下文中创建组件时,Angular 更喜欢从这些提供程序创建的服务实例,而不是应用程序根注入器的服务实例。

The first statement clearly indicates that I can access a root service anywhere in the app.第一条语句清楚地表明我可以在应用程序的任何位置访问根服务。 Whereas the second one is saying that the lazy loaded modules would get their own injector and potentially their own instances of the services?而第二个是说延迟加载的模块将获得自己的注入器,并可能拥有自己的服务实例?

So is this possible to get the singleton instance of the service in a lazy loaded module?那么这是否有可能在延迟加载的模块中获取服务的 singleton 实例?

if you are looking for only one instance through out the app you can specify如果您在整个应用程序中只寻找一个实例,您可以指定

@Injectable({
   providedIn: 'root',
})

this behaviour can also be overridden by specifying at app module src/app/app.module.ts (providers)此行为也可以通过在 app 模块src/app/app.module.ts (providers) 中指定来覆盖

The @Injectable() decorator identifies a service class. @Injectable()装饰器标识服务 class。 The providedIn property configures a specific ModuleInjector , here root , which makes the service available in the root ModuleInjector . providedIn属性配置了一个特定的ModuleInjector ,这里是root ,这使得服务在root ModuleInjector中可用。

Child ModuleInjectors are created when lazy loading other @NgModules .延迟加载其他@NgModules ModuleInjectors

Reference Link 参考链接

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM