为什么 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.

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

附言:这个代码在JiT模式下工作。

模块中不支持箭头函数(或lambdas(,因为AOT编译器需要能够"静态"分析模块。

使用普通的function而不是箭头函数应该可以解决问题:

export function myFactory(config) { };

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

你可以在官方指南或这份备忘单中找到更多关于AOT如何工作的信息。

最新更新