Reputation: 505
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.
Upvotes: 5
Views: 2114
Reputation: 505
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
var settings = {
SiteName: "MySite",
SiteApi: "http://site.api"
}
index.html
<script src="mysetting.js"></script>
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.
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.
Upvotes: 0
Reputation: 505
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);
}
Upvotes: 3