2

I would like to make facilitate the declaration of a provider by calling a static function like this :

const provider = MyModule.makeProvider();

@NgModule({
  bootstrap: [AppComponent],
  declarations: [AppComponent],
  imports: [
     ...
  ],
  providers: [
    provider,
    ...
  ],
})

but it fails with AOT (the provider is missing)

Whereas this is working :

const providers = [{provide : myToken, useValue: "value"}];

@NgModule({
  bootstrap: [AppComponent],
  declarations: [AppComponent],
  imports: [
     ...
  ],
  providers: [
    provider,
    ...
  ],
})
antoine
  • 93
  • 7
  • Possible duplicate of [Dynamic module/service configuration and AOT](https://stackoverflow.com/questions/42176090/dynamic-module-service-configuration-and-aot) – Bunyamin Coskuner Jan 30 '18 at 10:41

2 Answers2

1

Yes, this is because anything a module declares/uses should be statically analyzable for AOT to work. See this for further information

What do we understand by statically analyzable? It means another program does not have to run a function to understand what a certain value may be, as it can be inferred from the code itself. You cannot infer any return value from a function because of the famous Halting Problem

As you run a function to get the providers, AOT compiler will be confused. This also refers to dynamic templates/css style declarations

Community
  • 1
  • 1
Armen Vardanyan
  • 3,214
  • 1
  • 13
  • 34
1

As workaround I added a static function to my module. This function returns a ModuleWithProviders as follow :

import { NgModule, ModuleWithProviders } from '@angular/core';

// ....

public static withValue(value: string): ModuleWithProviders {
  return {
    ngModule: MyModule,
    providers: [
      { provide: MY_TOKEN, useValue: value},
    ],
};
antoine
  • 93
  • 7