我有一个带有核心软件包和主机软件包的Angular2应用程序。核心软件包用于主机软件包。
我正在开发一种在核心软件包中定义的身份验证服务。但是我想在主机软件包中使用服务。这样我就可以对整个应用程序使用身份验证。
我想使用核心软件包中定义的服务。谁能帮助如何实现这一目标?
uicore:
export class UICoreModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: UICoreModule,
providers: [
AuthGuardService,
AuthService
]
};
}
}
npm link .src
i在主机文件夹中进行npm link UI-Core
。
主机:
import { UICoreModule } from 'ui-core';
@NgModule({
imports:[
UICoreModule
],
providers:[
//how to use the AuthService from UICoreModule
]
})
export class HostModule { }
谢谢
您必须使用已创建的未来静态
import { UICoreModule } from 'ui-core';
@NgModule({
imports:[
UICoreModule.forRoot()
]
})
export class HostModule { }
我们缺乏您的uicoreModule装饰器可以确定的,但是全球模式是:
如果要创建一个模块导出多个组件/指令/管道和服务。您可以创建一个未来的静态方法(Forroot名称只是一个约定(,该方法将导出组件并提供您的注射量。如果这样做,您只需要从NGMODULE注释中删除提供商即可。
因此,在您的AppModule(或任何MainModule(中,您将使用forroot方法导入UicoreModule(这将导入组件并提供Alls Services(,并且如果您只需要在另一个模块中的UicoreModule中的组件,则只需定期导入它(只需定期导入它(没有未来的电话(。这种方式由UicoreModule提供的注射量只能实例化一次(又称Singleton(
更多详细信息(官方文档(
因此,如果您已导入UicoreModule(带有提供商,又称为uicoremodule.forroot(,则可以将您的服务注入任何构造函数,并在hostmodule中注入依赖项
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
}
}