从Angular js 2 Typescript访问web.config appsettings [英] Access web.config appsettings from Angular js 2 Typescript

查看:99
本文介绍了从Angular js 2 Typescript访问web.config appsettings的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是angular js 2类型脚本编程的新手.我试图找到一种从打字稿访问web.config的应用程序设置键的方法.我不想在我的类型脚本中对数据进行硬编码,因为它们会随环境的变化而变化. TIA

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

推荐答案

将Typescript编译为JavaScript,然后在使用web.config文件的应用程序上下文中执行该脚本.因此,您将无法在TypeScript级别读取配置.

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.

您需要做的是使配置在运行时可用.换句话说,无论TypeScript生成的代码是什么,都需要知道页面运行时可用的一些对象,这些对象将为它提供可能需要的任何配置.

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.

您可以使JS代码了解始终在全局上下文中存在的对象(例如,页面运行时JS中的appConfig).然后,可以使用设置填充该对象.假定剃刀的示例:

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"]';

然后您的TypeScript代码可以在运行时依赖于变量appConfig.

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

或者,您可以为页面提供一种将配置注入到TypeScript生成的代码中的方式:

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);
}

然后在您的页面中

<script type="text/javascript">
    SetAdminEmail('@ConfigurationManager.AppSettings["adminEmail"]');
    DisplayAdminEmail();
</script>

这篇关于从Angular js 2 Typescript访问web.config appsettings的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆