1

Working with angular for the first time in a long while and I'm trying something very new. I have a service, that I want to behave a bit differently based on how it's created, and I assumed that useFactory would be the right way to go, but I'm unsure that I've set it up properly.

So, I have the service defined and provided in the module like this:

@NgModule({
  declarations: [AdminBatchesComponent],
  imports: [
    CommonModule
  ],
  exports: [AdminBatchesComponent],
  providers: [
    {provide: BATCH_SERVICE_PROVIDER, useFactory: batchServiceProvider, deps: ['admin']},
  ]
})

and I have the Injection token defined like this:

export const BATCH_SERVICE_PROVIDER = new InjectionToken<BatchService>('BATCH_SERVICE_PROVIDER');

and the factory defined like this:

export function batchServiceProvider(source: string){
    return new BatchService(source);
}

and the constructor is setup like this:

export function batchServiceProvider(source: string){
    return new BatchService(source);
}

The main point of the source parameter is to have the service know what component called it to provide slightly different results based on that source. (i.e. different filtering etc.)

I am going to be updating this question with the full code in a live edit thing so the full thing can be made available

Chris Rutherford
  • 1,592
  • 3
  • 22
  • 58
  • Roughly equivalent to https://stackoverflow.com/questions/57465356/angular-7-build-prod-failed-with-error-cant-resolve-all-parameters-for/57466082#57466082. Basically, you can't depend on something that isn't provided but you can provide it easily – Aluan Haddad Aug 20 '19 at 21:12

1 Answers1

0

final solution:

@NgModule({
  declarations: [AdminBatchesComponent],
  imports: [
    CommonModule
  ],
  exports: [AdminBatchesComponent],
  providers: [
    {provide: ADMIN_BATCH, useValue: 'admin'}, //have a provider for the parameter in the service.
    {provide: BATCH_SERVICE_PROVIDER, useFactory: batchServiceProvider, deps: [ADMIN_BATCH]},
  ]
})
Chris Rutherford
  • 1,592
  • 3
  • 22
  • 58