Reputation: 103
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,
...
],
})
Upvotes: 2
Views: 449
Reputation: 103
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},
],
};
Upvotes: 1
Reputation: 3315
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
Upvotes: 1