2

I am currently using angular 2. I have my appsettings.json file like this.

"Dummies": {
  "Neck": "test,test1",
}

How can I read the value of Neck in typescript file?

2

2 Answers 2

2

Implement a server-side API controller that injects only the configuration you want from your appsettings.json and have your Angular client query the server for that information in ngOnInit(). And if this is an MVC app, use IConfiguration. Don't reference appsettings.json directly.

Require works, using it for appsettings.json is a really bad idea.

Basically at build time, you are bundling the entire contents of appsettings.json, including all the garbage you don't want from that file, and worse, all the connection strings, credentials, backdoor passwords, and secret stuff that you don't want to ever get out, and including them into your final main-client.js output. Even if you don't have any sensitive information there now, someone else will come along later and unknowingly compromise your security because generally we assume appsettings.json to be safely protected from end users. Not only is using require here reckless, you are effectively hard-coding your configuration into your product. That was probably not what you wanted.

Sign up to request clarification or add additional context in comments.

Comments

0

Apart from Antoine Guittet's suggestion, another simplistic approach is to use require as follows.

// import data from json file...
const data= require("path/to/your.json"); 

//... and then use it as regular object.
console.log(data);
console.log(data.Dummies.Neck);

I am assuming the json file to be as follows:

{
    "Dummies": {
        "Neck": "test,test1"
    }
}

1 Comment

You had better know what require does. DO NOT DO THIS WITH APPSETTINGS.JSON You probably have passphrases, connection strings, and other sensitive information there. Congratulations, you just packaged all of your passwords into main-client.js which is given to anyone who requests it without any sort of authentication. This will get you hacked faster than you can google Tony the Pony. And so, Children, this is why we do not copy-paste code from Stack Overflow that we don't understand.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.