[英]How to push configuration values from Asp.Net Core MVC 2.0 config file to React TypeScript client script?
I have an application on ASP.NET MVC Core 2.0
using React Template
. 我使用
React Template
在ASP.NET MVC Core 2.0
上有一个应用程序。 I have propertie in config file on server side - SiteURL
. 我在服务器端的配置文件中有属性 -
SiteURL
。 I need to push it to client TypeScript
, and don`t understand how can I make it? 我需要将它推送到客户端
TypeScript
,并且不知道我该如何制作它?
I tried to push them throw Home/Index
file by placing in the last script 我试图通过放入最后一个脚本来推送它们抛出
Home/Index
文件
SiteProps.SiteURL= "http://mysiteurl.org"
and on client I make 在我做的客户
export var SiteProps: { SiteURL: string } = {SiteURL: ""};
and import this file on boot 并在启动时导入此文件
But testing this property on console I see 但是我在控制台上测试这个属性
Uncaught ReferenceError: SiteProps is not defined
未捕获的ReferenceError:未定义SiteProps
I think that JavaScript
did't see my propertie from TypeScript
context. 我认为
JavaScript
从TypeScript
上下文中看到我的属性。
The question is how to make this code work, and what is the best practice to push const values (properties) to client TypeScript
code. 问题是如何使这个代码工作,以及将const值(属性)推送到客户端
TypeScript
代码的最佳实践是什么。
I found solution to make this line on Home/Index
: 我在
Home/Index
上找到了解决方案:
<div id="site-props" style="display: none;">@ViewBag.PropsJSON</div>
Where PropsJSON
is JSON
string of my configuration. 其中
PropsJSON
是我配置的JSON
字符串。 After it i initialize my clientscript configuration using this code: 之后,我使用以下代码初始化我的客户端配置:
function ImportProps() {
var ell = document.getElementById('site-props');
var jsontext = ell!.innerText;
SiteProps = JSON.parse(jsontext);
}
Some more ways how to solve it. 更多如何解决它的方法。
When application starts to rewrite file "mysetting.js" with actual settings and to ref this file in index.html
当应用程序开始使用实际设置重写文件“mysetting.js”并在
index.html
引用此文件时
mysetting.js mysetting.js
var settings = {
SiteName: "MySite",
SiteApi: "http://site.api"
}
index.html 的index.html
<script src="mysetting.js"></script>
In Home/Index
set window.settings in script block 在
Home/Index
在脚本块中设置window.settings
window.settings = {
SiteName: "MySite",
SiteApi: "http://site.api"
}
and it should be available from all code. 它应该可以从所有代码中获得。
After client application starts get all settings with fetch request from server on the fly, and get result as JSON object, and set it somewhere to static. 客户端应用程序启动后,即时获取来自服务器的获取请求的所有设置,并将结果作为JSON对象,并将其设置为静态。
fetch("api/Settings/getSettings").
then( /* set data to static */ )
Where you initialize your client code. 初始化客户端代码的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.