I'm working on an ionic2 project and I need to create a new custom JSON config file. I found some tutorials to create one and access it through http.get but I think it's weird to call it through a get request. I want it in the root folder (where all the config JSONs are) and I open/read the file directly.
I don't know if it's possible, or even recommended ? This is why I'm posting here to have some opinions and solutions :)
Thanks
After reading and reading different solutions I ended up using this hacky implementation. Hopefully there will be a nice and native solution available soon:
and then where ever needed, e.g.:
Personally I don't like the read the config.json file by using the http.get way to handle configuration information, and even though there must be another way to just include and read the json file in your code, since we're using Angular2 and Typescript, why not using classes, interfaces and doing it in a more fancy way?
What I'll show you next may seem more complicated than it should at first (although after reading it you will find it very straightforward and easy to understand), but when I started learning Angular2 I saw an example of how they handled config files in the Dependency Injection guide and I followed that in the apps I've worked on to handle config information (like API endpoints, default values, and so on).
According the docs:
So you would need to define a config object with the urls and so on, and then an
OpaqueToken
to be able to use it when injecting the object with your configuration.I included all my configuration in the
app-config.ts
fileWhat
OpaqueToken
is may be confusing at first, but it just a string that will avoid naming conflicts when injecting this object. You can find an amazing post about this here.Then, you just need to include it in the page you need it like this:
Please notice how to include it in the
providers
arrayAnd how to tell the injector how it should obtain the instance of the config object
UPDATE
OpaqueToken
has been deprecated since v4.0.0 because it does not support type information, useInjectionToken<?>
instead.So instead of these lines:
Now we should use