简体   繁体   中英

How to read values from appsettings.json to typescript file using angular2?

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?

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.

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"
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM