3

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.

ezain
  • 1,445
  • 1
  • 16
  • 32

1 Answers1

0

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.

255kb - Mockoon
  • 6,657
  • 2
  • 22
  • 29
  • the problem is not about the syntax. the compiler complains even if you rewrite with function syntax. The problem is about use an high order function (https://en.wikipedia.org/wiki/Higher-order_function) . My question is know if do this is technically impossible and why. ty – ezain Nov 05 '18 at 13:01
  • I must admit that I don't know the answer for higher order function. I just now that in my app I ended duplicating some code instead of generating it, and that I avoided at maximum these higher order functions – 255kb - Mockoon Nov 05 '18 at 14:22
  • could you go into a bit more depth with your initial sentence? I understand what static is, but not why it doesn't transpile first , nor why it matters specifically when in a decorator -- lambdas are allowed all-the-heck-over-the-place otherwise (and are in fact transpiled to static functions depending on your angular-cli build target) – roberto tomás Oct 02 '19 at 16:53