简体   繁体   English

如何使用angular2从appsettings.json读取typescript文件的值?

[英]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. 我目前正在使用角度2.我有这样的appsettings.json文件。

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

How can I read the value of Neck in typescript file? 如何读取打字稿文件中的Neck值?

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(). 实现服务器端API控制器,该控制器仅从appsettings.json注入所需的配置,并让您的Angular客户端在ngOnInit()中向服务器查询该信息。 And if this is an MVC app, use IConfiguration. 如果这是一个MVC应用程序,请使用IConfiguration。 Don't reference appsettings.json directly. 不要直接引用appsettings.json。

Require works, using it for appsettings.json is a really bad idea. 需要工作,将它用于appsettings.json是一个非常糟糕的主意。

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. 基本上在构建时,您正在捆绑appsettings.json的全部内容,包括您不希望从该文件中获取的所有垃圾,更糟糕的是,所有连接字符串,凭据,后门密码和您不需要的秘密内容想要永远离开,并将它们包含在最终的main-client.js输出中。 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. 即使您现在没有任何敏感信息,其他人也会在以后不知不觉地损害您的安全性,因为通常我们假设appsettings.json可以安全地受到最终用户的保护。 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. 除了Antoine Guittet的建议外 ,另一种简单的方法是使用require如下。

// 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: 我假设json文件如下:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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