简体   繁体   中英

Dependencies Injection angular 4 : my service not a singleton

I have a hard time to use an openId auth package with this config....

I have 3 modules :

module 1 : mainApplication module 2 : core module 3 : portal

I have a service (AuthService) in the core module, extending OAuthService from angular-oauth2-oidc.

It's just a way to isolate the dependency from angular-oauth2-oidc.

The mainApplication module is loading the portal & core service.

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

My portalModule:

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

My coreModule:

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

My config service :

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

It seems that the AuthService is instanciate more than one time...

And I lost the config beetween the moment where I configure the service and the moment I use it.

add the service (in providers) ONLY in the "Main Application". So, the imported modules in "Main Application" share the same service

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM