最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why do I have to export the function I use in angular appModule import module? - Stack Overflow

programmeradmin4浏览0评论

I have following code

@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/bar/']
      }
    })
  ],
  ...
})
export class AppModule { }

I have following code

@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./bar/']
      }
    })
  ],
  ...
})
export class AppModule { }

It works using ng serve, but I got following error when I run ng build --prod

ERROR in Error during template pile 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.

Then I modified my code to

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

And it's still not happy

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

At the end, I solved the issue by exporting the getToken function.

I have following question

  1. Why ng serve works but not ng build --prod?
  2. Why inline lambda doesn't work?
  3. Why do I have to export the function?
Share Improve this question asked May 13, 2018 at 1:11 ycshaoycshao 1,9684 gold badges22 silver badges32 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 9

The issues you are having are due to the Ahead-of-Time (AOT) piler in Angular. By default, ng serve and ng build use the Just-in-Time (JIT) piler. However, ng build --prod uses the AOT piler. You can simulate this same behavior doing ng serve --aot.

So, to your questions.

  1. See above explanation.
  2. The AOT Collector does not support the arrow function syntax.
  3. Angular generates a class factory in a separate module and that factory can only access exported functions.

Hope this helps!

发布评论

评论列表(0)

  1. 暂无评论