user6051680
user6051680

Reputation:

Passing Parameters to useFactory()

Practicing DI and Factory method, I want to pass some parameters to the Factory. So I wrote something like this:

const loggingImplementation: AnalyticsImplementation = {
  recordEvent: (metric: Metric): void => {
    console.log('The metric is:', metric);
    console.log('Sending to', destUrl);
  }
};

export function loggerFactory(http: HttpClient, destUrl: string): AnalyticsService {
  return new AnalyticsService(loggingImplementation);
}

@NgModule({
  imports: [CommonModule, HttpClientModule],
  providers: [
    {provide: 'API_URL', useValue: 'http://nsa.gov'},
    { provide: AnalyticsService, deps: [HttpClient, 'API_URL'], useFactory(http: HttpClient, destUrl: string): loggerFactory}
  ],
  declarations: [ ]
})

export class AnalyticsDemoModule1 {
}

But Angular gives me an error saying a semicolon is missing after loggerFactory so I think I am not using the correct syntax. Can you help tell me what I am doing wrong?

Upvotes: 1

Views: 2561

Answers (1)

Poul Kruijt
Poul Kruijt

Reputation: 71941

No need for the (http: HttpClient, destUrl: string):

useFactory: loggerFactory

If you want to inject a API_URL you can use a special notation:

{
  provide: AnalyticsService,
  deps: [ HttpClient, new Inject('API_URL') ],
  useFactory: loggerFactory
}

And it should work. Whatever you define in deps will be passed on to the factory parameters

Upvotes: 2

Related Questions