关于 Angular 和功能模块。
据此:
When we provide a service in a feature module that is eagerly loaded by our app's root module, it is available for everyone to inject.
这是否意味着该功能的所有组件都可用?或者其他功能模块的所有组件?
问题是我们在功能模块中有一项服务,我们能够将此服务注入(inject)其他功能模块。
我们的带有服务的功能模块:
@NgModule({
imports: [SharedModule],
declarations: [FeatureAComponent],
exports: [FeatureAComponent],
providers: [FeatureAService]
})
export class FeatureAModule { }
我们的没有服务的功能模块:
@NgModule({
imports: [SharedModule],
declarations: [FeatureBComponent],
exports: [FeatureBComponent],
providers: []
})
export class FeatureBModule { }
这里发生的事情是,我在 FeatureBComponent 中注入(inject)了 FeatureAService 并且它正在工作,为什么?我原以为它不起作用。
最佳答案
好的,现在我明白了。除非我理解错了。
因为我的功能模块是在根模块中导入的,所以我的提供程序可用于所有其他功能模块。
https://angular.io/guide/ngmodule#!#service-providers
官方有更具体的解释NgModule FAQs :
Providers listed in the
@NgModule.providers
of a bootstrapped module have application scope. Adding a service provider to@NgModule.providers
effectively publishes the service to the entire application.When you import a module, Angular adds the module's service providers (the contents of its providers list) to the application root injector.
This makes the provider visible to every class in the application that knows the provider's lookup token.
关于angular - 为 Angular 中的功能模块提供服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44735976/