1

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);
Drifter
  • 85
  • 1
  • 7

2 Answers2

1

Don't. Seriously, stay away from those two files (environment.ts and environment.prod.ts). Those are NOT about the DevOps meaning of the word "environment", they are about debug constants.

If you need to know if you're running a debug build, import isDevMode:

import { isDevMode } from '@angular/core';

If you need dynamic configuration, just read a Json from somewhere or have the server side inject it as a script tag, then read it directly or via Dependency Injection (it's not that hard to do).

But don't mess with those files. Trust me, you'll thank me later ;)

Alberto Chiesa
  • 7,022
  • 2
  • 26
  • 53
0

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();
Drifter
  • 85
  • 1
  • 7