【问题标题】:Angular2 how to use the service in providers from packaged module into another moduleAngular2如何使用提供者中的服务从打包的模块到另一个模块
【发布时间】:2018-08-03 10:38:20
【问题描述】:

我有一个带有核心包和主机包的 angular2 应用程序。核心包用于宿主包。

我正在开发一个在核心包中定义的身份验证服务。但我想服务在主机包中使用。这样我就可以对整个应用程序使用身份验证。

我想使用核心包中定义的服务。任何人都可以帮助如何实现这一目标?

UICore:

export class UICoreModule {

  static forRoot(): ModuleWithProviders {
    return {
      ngModule: UICoreModule,
      providers: [
        AuthGuardService,
        AuthService
      ]
    };
  }
 }

在npm link .\src 之后,我在主机文件夹中执行npm link UI-Core。

主持人:

 import { UICoreModule } from 'ui-core';

 @NgModule({
 imports:[
    UICoreModule
 ],
 providers:[
    //how to use the AuthService from UICoreModule 
 ]
 })
 export class HostModule { }

谢谢

【问题讨论】:

  • 我的理解是你不需要做任何事情——你现在可以访问导入模块的提供者,而不必将它们单独注入到你的宿主类中。当您尝试通过在类的业务逻辑中直接引用它们来访问它们时会发生什么?我相信它应该可以在您访问导入模块的提供者时起作用。
  • 还有什么是核心和主机“包”?我不熟悉这些
  • 有两个应用程序。 Host 是拥有所有根菜单和其他根样式的主机。核心包是特定于项目的应用程序。我构建并链接这个核心项目并创建一个包并在主机中使用它。宿主应用程序是我所做的 npm build:prod 和部署。
  • 谢谢。你为什么要使用forRoot?您的示例没有声明任何组件,您可以创建一个普通模块,并像往常一样声明提供者然后导入它吗?然后,提供程序应该可以直接用于使用核心模块的模块。

标签: angular angular-module


【解决方案1】:

你必须使用你创建的 forRoot 静态

import { UICoreModule } from 'ui-core';
@NgModule({
  imports:[
    UICoreModule.forRoot()
  ]
})
export class HostModule { }

我们缺少您的 UICoreModule 装饰器来确定这一点,但全局模式是:

如果您想创建一个导出多个组件/指令/管道和服务的模块。您可以创建一个 forRoot 静态方法(forRoot 名称只是一个约定),它将导出组件并提供您的 Injectable。如果你这样做,你只需要从 NgModule 注释中删除提供者。

因此,在您的 AppModule(或任何 MainModule)中,您将使用 forRoot 方法导入 UICoreModule(这将导入组件并提供所有服务),如果您只需要另一个模块中来自 UICoreModule 的组件,只需定期导入它(没有 forRoot 调用)。 这样 UICoreModule 提供的 Injectable 只会被实例化一次(又名 Singleton)

更多细节在这里(official doc)

因此,如果您已导入 UICoreModule(使用提供程序,也就是使用 UICoreModule.forRoot ),您只需在 HostModule 中使用 Dependencies Injection 将您的服务注入任何构造函数

 import { UICoreModule } from 'ui-core';
 @NgModule({
     imports:[
        UICoreModule.forRoot() // <- important
     ],
     declarations:[
        HostComponent // <- for example
     ],
 })
 export class HostModule {}

 <! ... inside your HostComponent ....>

 export class HostComponent {
      constrcutor(private authService: AuthService) {
           // to whatever you can with this.authService
      } 
 }

【讨论】:

  • 嗨,皮埃尔,这很有帮助,但是我们在这里只讨论使用模块,OP 不是关于组件,它是特定类型的 Angular 指令 - 你能否澄清你的答案是具体的只在模块之间使用多个提供者?
  • 由于 UICoreModule 被导入,您只需在 component/directive/pipe/whatsoever 构造函数中注入提供的可注入。构造函数(私有 authService:AuthService){...}
猜你喜欢
  • 1970-01-01
  • 2017-07-21
  • 1970-01-01
  • 2020-07-18
  • 2018-09-05
  • 1970-01-01
  • 2019-04-04
  • 1970-01-01
  • 2022-01-23
相关资源
最近更新 更多