Angular AoT compiler throw an error if you try to made a call in a decorator.
consider following code:
export function factoryBuilder(config: MyConfig) {
return function customFactory() {
return new MyService(config);
};
}
@NgModule({})
export class MyModule {
static forRoot(config: MyConfig): ModuleWithProviders {
return {
ngModule: MyModule,
providers: [
{
provide: MyService,
useFactory: factoryBuilder(config),
}]
};
}
}
If you try to build it with aot flag (--prod):
Compiler says:
ERROR in Error during template compile of 'AppModule'
Function expressions are not supported in decorators in 'MyModule'
...
Consider changing the function expression into an exported function.
Can someone explain technically why the compiler can't support that?
PS: This code works in JiT mode.
Arrow functions (or lambdas) are not supported in modules because AOT compiler needs to be able to analyze the module "statically".
Using a normal
function
instead of arrow function should solve the problem:You may also have to do the same thing with the
customFactory
function returned bymyFactory
.You can find more information about how AOT works in the official guide or in this cheat sheet.