从_layout.cshtml将常量值传递给Angular [英] Pass Constant Values to Angular from _layout.cshtml

查看:137
本文介绍了从_layout.cshtml将常量值传递给Angular的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,所以我在ASP.Net SPA项目的_Layout.cshtml中有一个常量变量,我希望将它们传递给Angular,以便他们可以访问这些变量.

Okay, so I have a constant variables in the _Layout.cshtml of ASP.Net SPA project and I would to pass them so that Angular will have access to those.

我该怎么做?

例如,这是我要转移的一个值.

For example, here is one value I am trying to transfer.

var lenderValues = @Html.Action("GetLenderDropdownValues", "Dropdown");

,这是我的第一个app.component启动的方式.

and here is how my first app.component boots up.

<my-rite-ui>Loading...</my-rite-ui>

我知道如何在AngularJS 1.x中仅使用常量并将其注入所需的常量,但是无法在Angular中弄清楚.

I know how to do it in AngularJS 1.x with just constant and injecting that constant whereever is needed, but couldn't figure it out in Angular.

任何帮助将不胜感激.

Any help will be highly appreciated.

推荐答案

这取决于您要确切执行的操作,但我看到两种可能性:

It depends on what you want exactly to do but I see two possibilities:

  • 定义常量

在导入主模块时需要传递此常量.而不可能在import本身上执行此操作.您可以导入一个函数并使用参数对其进行调用.

This constant needs to be passed when importing your main module. Whereas it's not possible to do this on the import itself. You can import a function and call it with parameters.

以下是引导您的应用程序的主要模块示例:

Here is a sample of the main module that bootstraps your application:

import {bootstrap} from '...';
import {provide} from '...';
import {AppComponent} from '...';

export function main(lenderValues) {
  bootstrap(AppComponent, [
    provide('lenderValues', { useValue: lenderValues })
  ]);
}

然后您可以从HTML主页中将其导入,如下所示:

Then you can import it from your HTML main page like this:

<script>
  var lenderValues = @Html.Action("GetLenderDropdownValues", "Dropdown");
  System.import('app/main').then((module) => {
    module.main(lenderValues);
  });
</script>

然后,您的lenderValues可以注入组件之类的所有元素中:

Your lenderValues can be then injected in all elements like a component:

@Component({
  (...)
})
export class SomeComponent {
  constructor(@Inject('lenderValues') lenderValues) {
  }
}

  • my-rite-ui元素上定义参数
    • Define a parameter on my-rite-ui element
    • 您可以在此级别指定参数,但无法对其进行评估.因此,这比较麻烦,因为您需要使用JSON.stringify将其序列化为字符串,从相应的ElementRef中获取组件中的元素,然后使用JSON.parse反序列化.

      You can specify a parameter at this level but it can't be evaluated. So it's a bit more tedious since you need to serialize it as string with JSON.stringify, gets the element in your component from its corresponding ElementRef and deserialize it using JSON.parse.

      然后,您可以将数据添加为提供者.

      Then you can add the data as a provider.

      这篇关于从_layout.cshtml将常量值传递给Angular的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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