【问题标题】:Dependencies Injection angular 4 : my service not a singleton依赖注入角度 4:我的服务不是单例
【发布时间】:2017-09-25 15:08:58
【问题描述】:

我很难在这个配置中使用 openId auth 包....

我有 3 个模块:

模块 1:mainApplication 模块 2:核心 模块 3:门户

我在核心模块中有一个服务(AuthService),从 angular-oauth2-oidc 扩展 OAuthService。

这只是一种将依赖项与 angular-oauth2-oidc 隔离的方法。

mainApplication 模块正在加载门户和核心服务。

@NgModule({
  declarations: [
  ],
  entryComponents: [ 
  ],
  imports: [
    CommonModule,
    IsocialCoreModule.forRoot(),
    IsocialPortalModule.forRoot(portalConfig),
  ])}
  export class MyMainApp {}

我的门户模块:

...
  imports: [
    MyCoreModule,
  ],
})
export class MyPortalModule {
  static forRoot(config: PortalConfig): ModuleWithProviders {
    return {
      ngModule: PortalModule,
      providers: [ConfigService, 
                 {provide: PortalConfigToken, useValue: config}, 
                 AuthService] // --> Error if not added
    };
  }
}

我的核心模块:

@NgModule({
  imports: [
    HttpModule,
    OAuthModule.forRoot()
  ],
  declarations: [],
})
export class MyCoreModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: MyCoreModule,
      providers: [BasicGuardService, AuthService // Error if not added]
    };
  }
}

我的配置服务:

  constructor(@Inject(PortalConfigToken) private portalConfig: PortalConfig, private authService: AuthService) {
    this.config = this.portalConfig;
    this.authService.configure(this.portalConfig.authConfig);
  }

好像 AuthService 实例化了不止一次...

我在配置服务和使用它的那一刻之间丢失了配置。

【问题讨论】:

    标签: angular dependency-injection angular2-services angular-oauth2-oidc


    【解决方案1】:

    仅在“主应用程序”中添加服务(在提供程序中)。因此,“主应用程序”中的导入模块共享相同的服务

    【讨论】:

    • 我试过了。但是这样做我有一个例外,说提供者没有定义。
    • ERROR 错误:没有 AuthService 提供者!我必须将其添加为 Core、Portal 和 MainApp 中的依赖项
    • 对不起,我是 Angular4 的小新手。我认为如果你使用 mainApplication, @NgModule({declarations: [..],imports[..],providers[AuthService]..)} 你只需要在你需要的组件中导入 AuthService
    • 是的。我也是这么想的。
    猜你喜欢
    • 2017-11-11
    • 2018-10-16
    • 2020-04-24
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多