Can't inject service into Angular Provider UseFactory

Viewed 664

Some background information: I have created a generated API Client with Nswag and ASP Net Core. To set the base url for the api client, the following code is used:

export const API_BASE_URL = new InjectionToken<string>(
  "API_BASE_URL"
);

@Injectable({
  providedIn: "root",
})
export class ApiClient {
  // Omitting code for brevity

  constructor(
    @Inject(HttpClient) http: HttpClient,
    @Optional() @Inject(API_BASE_URL) baseUrl?: string
  ) {
    this.http = http;
    this.baseUrl = baseUrl !== undefined && baseUrl !== null ? baseUrl : "";
  }
  
  // Etc..
}

Now I need to register that API_BASE_URL so it can be injected into the NotificatiesClient. I have done the following in my app.module.ts:

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, AppRoutingModule, HttpClientModule],
  providers: [
    {
      provide: NOTIFICATIESERVICE_API_BASE_URL,
      useFactory: (serviceToInject: ServiceToInject) => serviceToInject.GetBaseUrl(),
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

and let's say ServiceToInject is a service like this:

// Note 1: I tried with providedIn: 'root', but that did not make a difference.
// Note 2: This one is stored in src/app/core/services/ServiceToInject.service.ts
@Injectable()
export class ServiceToInject{
  // Service here
}

But when I try to register a provider for API_BASE_URL in my app.module.ts with the following code:

providers: [
  {
    provide: API_BASE_URL,
    useFactory: (serviceToInject: ServiceToInject) => serviceToInject.GetBaseUrl(),
  },
],

I get an Can't resolve all parameters for useFactory error.

Anyone knows how to fix this?

1 Answers

The answer, in my case, was very easy!

The provider code needs a property called deps with the types of the dependencies I am using in my useFactory, like so:

{
  provide: NOTIFICATIESERVICE_API_BASE_URL,
  deps: [AppConfigService],
  useFactory: (serviceToInject: ServiceToInject) => serviceToInject.GetBaseUrl(),
},

I hope it helps you guys out!

Related