为什么我必须导出我在angular appModule导入模块中使用的函数?

时间:2018-05-13 01:11:16

标签: javascript angular

我有以下代码

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    RoutingModule,
    SharedModule,
    JwtModule.forRoot({
      config: {
        headerName: 'Authorization',
        tokenGetter: () => localStorage.getItem('token’), // <———— this line has problem
        whitelistedDomains: ['localhost:4200']
        //blacklistedRoutes: ['localhost:3001/auth/', 'foo.com/bar/']
      }
    })
  ],
  ...
})
export class AppModule { }

它使用ng serve,但我在运行ng build --prod

时出现以下错误
ERROR in Error during template compile of 'AppModule'
  Function expressions are not supported in decorators in 'ɵ0'
    'ɵ0' contains the error at app/app.module.ts(36,22)
      Consider changing the function expression into an exported function.

然后我将代码修改为

function getToken() {
  return localStorage.getItem('token')
}
…
JwtModule.forRoot({
      config: {
        headerName: 'Authorization',
        tokenGetter: () => getToken, 
        whitelistedDomains: ['localhost:4200’]
...

它仍然不高兴

ERROR in app/app.module.ts(19,10): Error during template compile of 
'AppModule'
  Reference to a non-exported function.

最后,我通过导出getToken函数解决了这个问题。

我有以下问题

  1. 为什么ng serve有效但ng build --prod
  2. 为什么内联lambda不起作用?
  3. 为什么我必须导出该功能?

1 个答案:

答案 0 :(得分:1)

您遇到的问题归因于Angular中的Ahead-of-Time (AOT)编译器。默认情况下,ng serveng build使用即时(JIT)编译器。但是,ng build --prod使用AOT编译器。您可以通过ng serve --aot来模拟相同的行为。

所以,你的问题。

  1. 请参阅上面的说明。
  2. AOT收集器不支持箭头 功能 syntax
  3. Angular在单独的模块中生成一个类工厂,并且 工厂只能访问exported functions

希望这会有所帮助!

相关问题