加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – 将asp.net服务器参数传递给Angular 2 app

发布时间:2020-12-15 19:16:03 所属栏目:asp.Net 来源:网络整理
导读:================================================== ============== 编辑:解决方案升级到2.0 Final – Passing server parameters to ngModule after RC5 upgrade ================================================== ================ 有没有将服务器参
================================================== ==============

编辑:解决方案升级到2.0 Final – Passing server parameters to ngModule after RC5 upgrade

================================================== ================

有没有将服务器参数传递给Angular 2应用程序的方法?

即我想使用MVC对象“HttpContext.User.Identity.Name”并在我的angular 2应用程序中的任何位置注入它.

在角度1中,这可以使用ng“.constant”并将.Net对象序列化为index.cshtml中的JSON.

看起来有一种方法可以传递params,但这不适用于.Net代码.
Define global constants in Angular 2

//HTML - Bootstrapping
        <script>

            System.import('app/main').then(null,console.error.bind(console));
            //I WOULD LIKE TO PASS SOME PARAMS TO APP/MAIN HERE
        </script>

最终解决方案:(非常感谢蒂埃里)

index.cshtml:

<script>
    System.import('app/main').then(
        module => 
            module.main(
                {
                    name: '@User.Identity.Name',isAuthenticated: User.Identity.IsAuthenticated.ToString().ToLowerInvariant(),}
            ),console.error.bind(console)
    );
</script>

main.ts:

...
    import {provide} from '@angular/core';
...

    export function main(params) {
        bootstrap(AppComponent,[
                provide('Name',{ useValue: params.name }),provide('IsAuthenticated',{ useValue: params.isAuthenticated }),ROUTER_PROVIDERS,HTTP_PROVIDERS,LoggerService,AuthenticationService
            ]);
    }

用法:

import {Component,Injectable,Inject} from '@angular/core';
import {ROUTER_DIRECTIVES} from '@angular/router';

@Component({
    selector: 'navbar',templateUrl: 'app/components/header/navbar.html',directives: [ROUTER_DIRECTIVES]
})
export class SomeComponent {

    constructor(@Inject('Name') public username: string) {

    }

}

解决方法

一个选项是在您导入的模块中添加方法.因此,您可以调用它来提供您想要的对象.

以下是app / main模块的示例:

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

export function main(params) {
  let userIdentityName = params.name; // for example
  bootstrap(AppComponent,[
    provide('userIdentityName',{ useValue: userIdentityName })
  ]);
}

然后你可以从HTML主页面导入它,如下所示:

<script>
  System.import('app/main').then((module) => {
    module.main({
      userIdentityName: 'something from asp.net'
    });
  });
</script>

更新

使用最新版本的Angular,您需要以这种方式利用模块:

export const USER_IDENTITY_NAME_TOKEN =
  new  InjectionToken('userIdentityName');

@NgModule({
  (...)
  providers: [
    {
      provide: USER_IDENTITY_NAME_TOKEN,useValue: userIdentityName
    }
  ]
})
export class MainModule() { }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读