How to push configuration values from Asp.Net Core MVC 2.0 config file to React TypeScript client script?

前提是你 提交于 2019-12-10 16:25:40

问题


I have an application on ASP.NET MVC Core 2.0 using React Template. I have propertie in config file on server side - SiteURL. I need to push it to client TypeScript, and don`t understand how can I make it?

I tried to push them throw Home/Index file by placing in the last script

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

I think that JavaScript did't see my propertie from TypeScript context.

The question is how to make this code work, and what is the best practice to push const values (properties) to client TypeScript code.


回答1:


I found solution to make this line on Home/Index:

<div id="site-props" style="display: none;">@ViewBag.PropsJSON</div>

Where PropsJSON is JSON string of my configuration. 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);
}



回答2:


Some more ways how to solve it.

One.

When application starts to rewrite file "mysetting.js" with actual settings and to ref this file in index.html

mysetting.js

var settings = {
  SiteName: "MySite",
  SiteApi: "http://site.api"
}

index.html

<script src="mysetting.js"></script>

Two.

In Home/Index set window.settings in script block

window.settings = {
  SiteName: "MySite",
  SiteApi: "http://site.api"
}

and it should be available from all code.

Three.

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.

fetch("api/Settings/getSettings").
   then( /* set data to static */ )

Where you initialize your client code.



来源:https://stackoverflow.com/questions/47247442/how-to-push-configuration-values-from-asp-net-core-mvc-2-0-config-file-to-react

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!