How to make an Angular app witch Universal SSR use dynamic configurations from json file?

4/16/2019

I was assigned the task of making a dynamic load of settings for the Angular application from the JSON file on the server during the application start. The peculiarity is that the application uses server rendering with Universal. I tried to do this for the browser using this method. https://juristr.com/blog/2018/01/ng-app-runtime-config But it works only for the browser app rendering. How to do it for server-side rendering?

-- valery_vitkus
angular
javascript
kubernetes

2 Answers

4/16/2019

You could use the following package

https://www.npmjs.com/package/runtime-config-loader

-- S edwards
Source: StackOverflow

4/16/2019

The most likely culprit here is that you're loading json file from relative path but Universal does not currently support relative urls but only absolute.

So you can provide absolute path to your json file:

server.ts

app.engine('html', (_, options, callback) => {
  const protocol = options.req.protocol;
  const host = options.req.get('host');

  const engine = ngExpressEngine({
    bootstrap: AppServerModuleNgFactory,
    providers: [
      provideModuleMap(LAZY_MODULE_MAP),
      { provide: 'APP_BASE_URL', useFactory: () => `${protocol}://${host}`, deps: [] },
    ]
  });
  engine(_, options, callback);
});

your.service.ts

@Injectable()
export class ConfigProvider {
  config: Config;

  constructor(
    private http: HttpClient,
    @Inject(PLATFORM_ID) private platformId: {},
    @Inject('APP_BASE_URL') @Optional() private readonly baseUrl: string
  ) {
    if (isPlatformBrowser(platformId)) {
      this.baseUrl = document.location.origin;
    }
  }

  loadConfig() {
    return this.http.get<Config>(
      `${this.baseUrl}/assets/plugins-config.json`
    );
  }
}

For more details see example of project that also uses APP_INITIALIZER to load config

-- yurzui
Source: StackOverflow