mercredi 21 août 2019

Angular Service Factory pattern

I am trying to deploy a new module for work and I am stuck on how to implement the design pattern for my service.

To be specific I have a generic class called 'LoggerService' which gets extended by my services for console logging and database logging. I now want to be able to export the whole module and fetch it from a proxy within the company. The publishing and fetching works, but now the problem is that when I want to instantiate either one of the concrete services, angular tells me that this service was not exported. `

@NgModule({
  declarations: [NgxCmLoggerComponent],
  imports: [NgxCmHttpModule
  ],
  exports: [NgxCmLoggerComponent],
  providers: [NgxCmDatabaseLoggerService, NgxCmConsoleLoggerService]
})
export class NgxCmLoggerModule { 
  static forRoot(config: NgxCmLoggerService): ModuleWithProviders {
    return {
      ngModule: NgxCmLoggerModule,
      providers: [
        {provide: NgxCmLoggerService, useClass: config}
      ]
    };
  }
}`

This is how my module looks like, as you can see I am providing both Services and I have the forRoot method to instantiate the service I want for the use case. `

NgxCmLoggerModule.forRoot(new NgxCmConsoleLoggerService),

` That's how I am trying to instantiate my service, in this case, the console logger. When I try this, angular signals me that the ConsoleLoggerService, which should be provided by the module, is not available. I am pretty sure I am doing something wrong with respect to the forRoot method, I just don't know what.

I am happy for any help, thank you, Chris.

Aucun commentaire:

Enregistrer un commentaire