4

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.

Dmitrij Polyanin
  • 485
  • 5
  • 23
  • If you are Server Side Rendering or app you could pass it as a prop to the main component, otherwise, if no SSR is being made you'll have to hard code it in the front-end code. Another approach could be using your webpack configuration to read the web.config and create a variable with the value. – afnpires Nov 12 '17 at 11:23
  • On server renders only Home/Index and i can not push values directly to main component from C#, and it builds on TypeScript compiler and webpack to complete js script, so i can't pass value using razor, as i think. Hardcode on client is varian but Last variant, because i don`t like two places of identical config. Webpack aproach is interesting, but How? – Dmitrij Polyanin Nov 12 '17 at 11:49
  • And i found one way. not so hard to make what I need. Using `div` and `json`, see my answer. But loooking other ways. – Dmitrij Polyanin Nov 12 '17 at 11:54

2 Answers2

3

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);
}
Dmitrij Polyanin
  • 485
  • 5
  • 23
0

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.

Community
  • 1
  • 1
Dmitrij Polyanin
  • 485
  • 5
  • 23