为什么Angular AoT在装饰器中不支持函数表达式?

时间:2018-11-05 11:09:33

标签: javascript angular lambda functional-programming angular-aot

如果您尝试在装饰器中进行调用,Angular AoT编译器将引发错误。

考虑以下代码:

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),
        }]
    };
  }
}

如果您尝试使用aot标志(--prod)构建它:

编译器说:

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.

有人可以从技术上解释为什么编译器不支持吗?

PS:此代码在JiT模式下工作。

1 个答案:

答案 0 :(得分:0)

模块中不支持箭头功能(或lambda),因为AOT编译器需要能够“静态”分析模块。

使用普通的function代替箭头功能可以解决此问题:

export function myFactory(config) { };

您可能还需要对customFactory返回的myFactory函数执行相同的操作。

您可以在official guide或此cheat sheet中找到有关AOT工作原理的更多信息。

相关问题