Sergey
Sergey

Reputation: 7692

Angular 8: Function expressions are not supported in decorators

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)

Upvotes: 5

Views: 2542

Answers (2)

user4676340
user4676340

Reputation:

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)

Upvotes: 5

yurzui
yurzui

Reputation: 214047

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
},

Upvotes: 2

Related Questions