javascriptangularangular-aot

Exporting variable in angular AoT compiler


I tried to implement dynamic configuration as can be seen in this post.

Everything works in JiT compiler, but I get

ERROR in Error during template compile of 'environment'
  Function calls are not supported in decorators but 'Environment' was called.

when trying to build with the AoT compiler.

This is my environment.ts (note class Environment is exported):

export class Environment extends DynamicEnvironment {
  public production: boolean;

  constructor() {
    super();
    this.production = false;
  }
}

export const environment = new Environment();

I would still like to use the environment in the standard way some.component.ts:

import { environment } from '../environments/environment';

console.log(environment.config.property);

Solution

  • Solved this by creating config.module.ts and config.service.ts. Config module declares providers:

    @NgModule({
      providers: [
        ConfigService,
        {
          provide: APP_INITIALIZER,
          useFactory: (appConfigService: ConfigService) => () => appConfigService.loadAppConfig(),
          deps: [ConfigService],
          multi: true,
        },
      ],
    })
    export class ConfigModule {}
    

    Usage of config service in some.component.ts:

    @Component(...)
    export class SomeComponent {
      constructor(private configService: ConfigService) { }
    
      private myMethod() {
        console.log(this.configService.get.property);
      }
    }
    

    For tests, json testing config file is imported:

    import { default as appTestConfig } from '../../../../assets/app-config.test.json';
    

    and set directly on config service:

    TestBed.configureTestingModule({
      ...,
      imports: [
        ConfigModule,
        ...
      ],
      providers: [
        {
          provide: APP_INITIALIZER,
          useFactory: (appConfigService: ConfigService) => () => appConfigService.setConfig(appTestConfig),
          deps: [ConfigService],
          multi: true,
        },
      ]
    }).compileComponents();