0

I am new to angular js 2 type script programming. I am trying to find out a way to access app settings keys of web.config from typescript. I wouldn't want to hardcode the data in my type script as they vary across environments. TIA

3
  • use C# to read and pass it to your js. Commented Nov 8, 2016 at 14:47
  • I created the C# class for reading the web.config values but I don't know how to pass those values to my typescript file. Commented Nov 29, 2016 at 10:29
  • Because TypeScript is transpiled into JavaScript, you won't be able to read the configuration file. You could either use Razor syntax to inject the proper value in a script tag, or you could write a Powershell script to replace the values during build. stackoverflow.com/questions/38000449/… Commented Feb 3, 2017 at 1:44

1 Answer 1

1

Typescript is compiled to JavaScript which later gets executed within the context of the application consuming the web.config file. Because of this, you won't be able to read the configuration at the TypeScript level.

What you need to do instead is make the configuration available at runtime. In other words, whatever code is generated by TypeScript needs to be aware of some object available while the page is running that will feed it any configuration it may need.

There a few ways to do this.

You could make your JS code aware of an object that should always exist in the global context (e.g. appConfig in JS when the page is running). You can then populate this object with the settings. Example asuming Razor:

var appConfig = [];
appConfig.adminEmail = '@ConfigurationManager.AppSettings["adminEmail"]';

Then your TypeScript code can rely on variable appConfig at runtime.

Alernatively, you can device a way for your page to inject the configuration into the code generated by your TypeScript:

var adminEmail;

function SetAdminEmail(val: string) 
{
    adminEmail = val;
}

function DisplayAdminEmail() 
{
    alert(adminEmail);
}

Then in your page:

<script type="text/javascript">
    SetAdminEmail('@ConfigurationManager.AppSettings["adminEmail"]');
    DisplayAdminEmail();
</script>
Sign up to request clarification or add additional context in comments.

1 Comment

The example in this to inject data into main - plnkr.co/edit/ojaneZSSihUvkLmrpNkh?p=preview . The challenge is to read appsettings configuration data in index.html. We are just using angular2 on the client side without mvc. Any inputs on this would be appreciated.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.