angular - 为 Angular 中的功能模块提供服务

标签 angular

关于 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/

相关文章:

angular - 有没有办法为同一个 Angular 应用程序组合 CSR 和 SSR?

angular - 如何使用 Visual Studio 2017 调试 Angular 2

angular - 如何更改 Angular 2 应用程序中的默认图标图标?

javascript - MEAN.JS View 不显示链接是否在新选项卡/窗口中打开

javascript - VS Code 强制使用分号,但 Angular TypeScript 示例的使用不一致?

angular - 如何在表单中正确预填写下拉列表?

angular - 如何更改 Angular Material 步进器步骤图标的颜色

Angular - Observables 组合结果多次调用

angular - 如何使用angular2的路由器实现面包屑

Angular 刷新组件