Angular2如何使用提供者中的服务从打包模块到另一个模块

时间:2018-02-23 11:21:55

标签: angular angular-module

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

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

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

UICore:

html_nodes(webpage.2, ".bookie")

export class UICoreModule { static forRoot(): ModuleWithProviders { return { ngModule: UICoreModule, providers: [ AuthGuardService, AuthService ] }; } } 之后我在主机文件夹中npm link .\src

主机:

npm link UI-Core

由于

1 个答案:

答案 0 :(得分:0)

您必须使用已创建的forRoot静态

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

我们缺少你的UICoreModule装饰器,但全局模式是:

如果要创建导出多个组件/指令/管道和服务的模块。您可以创建一个forRoot静态方法(forRoot name只是一个约定),它将导出组件并提供您的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
      } 
 }