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

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 将asp.net服务器参数传递给Angular 2 app前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
================================================== ==============

编辑:解决方升级到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() { }
原文链接:https://www.f2er.com/aspnet/246574.html

猜你在找的asp.Net相关文章