Angular 8: Function expressions are not supported in decorators

Viewed 2314

I'm having trouble trying to build prod build in Angular 8. The error is

ERROR in Error during template compile of 'AppModule'
  Function expressions are not supported in decorators in 'SocketLibModule'
    'SocketLibModule' references 'initializeApp'
      'initializeApp' contains the error at ../socket-lib/src/lib/socket-lib.module.ts(9,12)
        Consider changing the function expression into an exported function.

What points to my lib

export const SOCKET_CONFIG = new InjectionToken<SocketConfig>('SOCKET_CONFIG');

export function initializeApp(socketConfig: SocketConfig) {
  return (uriConfig: any) => {
    return () => uriConfig.load(socketConfig);
  };
}

@NgModule()
export class SocketLibModule {
  public static forRoot(socketConfig: SocketConfig): ModuleWithProviders {
    return {
      ngModule: SocketLibModule,
      providers: [
        {
          provide: SOCKET_CONFIG,
          useValue: socketConfig
        },
        {
          provide: APP_INITIALIZER,
          useFactory: initializeApp(socketConfig),
          deps: [ConfigInitService, HttpClientModule],
          multi: true
        },
        HttpClientModule
      ]
    };
  }

}

The error point (9,12) refers to this return (uriConfig: any) => { just at opening parenthesis.

I've tried to change arrow functions into regular but nothing has changed as well as error point (9,12)

2 Answers
useFactory: initializeApp(socketConfig),

This line is the issue.

The app initializer should be a factory : this means it should be

useFactory: initializeApp,

Otherwise, you are returning a function call, which is forbidden in typescript decorators (not just in Angular, or it's 8th version)

AOT only supports limited functions call.

You can use already provided SOCKET_CONFIG instead of wrapping factory in another function:

export function initializeApp(uriConfig: ConfigInitService, socketConfig: SocketConfig) {
   return uriConfig.load(socketConfig);
}

Provider should look like:

{
    provide: APP_INITIALIZER,
    useFactory: initializeApp,
    deps: [ConfigInitService, SOCKET_CONFIG],
    multi: true
},
Related