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
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]},
]
})