访问 Angular 延迟加载模块中的根服务
Access root services in Angular lazy loaded module
我正在玩 Angular 延迟加载模块,想访问延迟加载模块中的根服务 AuthService
。我想访问延迟加载模块中根注入器中存在的单例实例。
我正在关注 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. 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.
第一个语句清楚地表明我可以在应用程序的任何位置访问根服务。而第二个是说延迟加载的模块将获得自己的注入器,并可能获得自己的服务实例?
那么是否可以在惰性加载模块中获取服务的单例实例?
如果您在整个应用程序中只查找一个实例,您可以指定
@Injectable({
providedIn: 'root',
})
此行为也可以通过在应用程序模块中指定来覆盖
src/app/app.module.ts
(提供商)
@Injectable()
装饰器标识服务 class。 providedIn
属性 配置了一个特定的 ModuleInjector
,这里是 root
,这使得服务在 root
ModuleInjector
.
中可用
子 ModuleInjectors
是在延迟加载其他 @NgModules
时创建的。
我正在玩 Angular 延迟加载模块,想访问延迟加载模块中的根服务 AuthService
。我想访问延迟加载模块中根注入器中存在的单例实例。
我正在关注 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. 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.
第一个语句清楚地表明我可以在应用程序的任何位置访问根服务。而第二个是说延迟加载的模块将获得自己的注入器,并可能获得自己的服务实例?
那么是否可以在惰性加载模块中获取服务的单例实例?
如果您在整个应用程序中只查找一个实例,您可以指定
@Injectable({
providedIn: 'root',
})
此行为也可以通过在应用程序模块中指定来覆盖
src/app/app.module.ts
(提供商)
@Injectable()
装饰器标识服务 class。 providedIn
属性 配置了一个特定的 ModuleInjector
,这里是 root
,这使得服务在 root
ModuleInjector
.
子 ModuleInjectors
是在延迟加载其他 @NgModules
时创建的。