7

What is the approved way of externalizing string constant in Angular 2 application, or in JavaScript application in general? I mean something like .properties file in Java, where backend connection attributes are stored.

As far as I know, JavaScript doesn't support reading from file in client end easily. My current solution is to use injectable service class, which stores key-value pairs as an object attributes. Then I just inject the service in other services which needs those values. Is this justifiable method, or does JavaScript/A2 provide some more uniform way to handle value injection?

Tuomas Toivonen
  • 21,690
  • 47
  • 129
  • 225

1 Answers1

0

I think that the way to do is the right one.

You could bootstrap asynchronously after your request(s) complete(s). Here is a sample:

var app = platform(BROWSER_PROVIDERS)
  .application([BROWSER_APP_PROVIDERS, appProviders]);

var service = app.injector.get(ConfigService);

service.getConfig().flatMap((config) => {
  var configProvider = new Provider('config', { useValue: config });
  return app.bootstrap(appComponentType, [ companiesProvider ]);
}).toPromise();

See this question:

I see another approach if you're able to update index.html page (the main entry point) on the server side. Here is a sample:

<script>
  var params = {"token": "@User.Token", "xxx": "@User.Yyy"};
  System.import('app/main').then((module) => {
    module.main(params);
  });
</script>

See this question:

You could also register an APP_INITIALIZER provider for this:

provide(APP_INITIALIZER, {
  useFactory: (service:ConfigService) => () => service.loadConfig(), 
  deps:[ConfigService, HTTP_PROVIDERS],
  multi: true}),

See this issue for more details:

Community
  • 1
  • 1
Thierry Templier
  • 198,364
  • 44
  • 396
  • 360