Why Angular AoT don't supports function expressions in decorators?

1.1k views Asked by At

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.

1

There are 1 answers

3
255kb - Mockoon On

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:

export function myFactory(config) { };

You may also have to do the same thing with the customFactory function returned by myFactory.

You can find more information about how AOT works in the official guide or in this cheat sheet.