How to use "APP_INITIALIZER" into a library with standalone components

96 views Asked by At

In my angular library (library word is very important here!) I've it :

@NgModule({
    imports: [CommonModule],
    providers: [
        {
          provide: APP_INITIALIZER,
          deps: [TreatmentDeclaratorServiceSpecificImpl],
          useFactory() {
            return async () => Promise.resolve();
          },
          multi: true
        },
        TreatmentDeclaratorServiceSpecificImpl
    ]
})
export class TreatmentDeclaratorModule { }

The goal is to force Angular to instanciante TreatmentDeclaratorServiceSpecificImpl, also if application not import the service.

How can I do it with an application which use standalone components? Application is forced to declare all theses classes into his bootstrap function??

The APP_INITIALIZER was transparent for application, I wish this was still the case with standalone components.

Its possible?

Regards

1

There are 1 answers

1
Bojan Kogoj On

This is how I would do it

export const provideTreatment = (): EnvironmentProviders => {
  const providers: (Provider | EnvironmentProviders)[] = [
    TreatmentDeclaratorServiceSpecificImpl,
    {
      provide: APP_INITIALIZER,
      deps: [TreatmentDeclaratorServiceSpecificImpl],
      useFactory() {
        return async () => Promise.resolve();
      },
      multi: true
    },
  ];

  return makeEnvironmentProviders(providers);
};

And use in AppModule or ApplicationConfig

providers: [
  provideTreatment(),
  ...
]

Maybe take a look at how Router and HttpClient do this.