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

时间:2016-05-20 02:51:57

标签: asp.net-mvc asp.net-web-api angular

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

编辑:解决方案升级到2.0决赛后 - Passing server parameters to ngModule after RC5 upgrade

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

是否可以将服务器参数传递给Angular 2应用程序?

即。我想使用MVC对象“HttpContext.User.Identity.Name”并将其注入我的angular 2 app中的任何位置。

在角度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) {

    }

}

3 个答案:

答案 0 :(得分:8)

选项是在导入的模块中添加方法。所以你可以调用它来提供你想要的对象。

以下是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() { }

答案 1 :(得分:4)

感谢有关使用platformBrowserDynamic启动的人的信息:

main.ts:

//platformBrowserDynamic().bootstrapModule(asstModule);

export function main(appSettings: any) {   
    platformBrowserDynamic([{ provide: 'AppSettings', useValue: appSettings }]).bootstrapModule(asstModule);
}

//platformBrowserDynamic().bootstrapModule(asstModule); export function main(appSettings: any) { platformBrowserDynamic([{ provide: 'AppSettings', useValue: appSettings }]).bootstrapModule(asstModule); }

答案 2 :(得分:0)

使用.NET Core服务器,我建议使用IOptions<>ViewComponent

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // ...

    services.AddOptions();
    services.Configure<Models.EnvironmentSettings>(Configuration.GetSection("client"));
    services.Configure<Models.EnvironmentSettings>(options =>
    {
        options.OtherSetting = "Other";
    });

    services.AddMvc();
}

模型/ EnvironmentSettings.cs

public class EnvironmentSettings
{
    public string OtherSetting { get; set; }
    public string LoginUrl { get; set; }
}

appsettings.json

{
    "client": {
        "LoginUrl": "http://localhost:45290/Token"
    }
}

控制器/组件/ BootstrapViewComponent.cs

public class BootstrapViewComponent : ViewComponent
{
    private IOptions<EnvironmentSettings> environmentSettings;

    public BootstrapViewComponent(
        IOptions<EnvironmentSettings> environmentSettings
    )
    {
        this.environmentSettings = environmentSettings;
    }

    public async Task<IViewComponentResult> InvokeAsync()
    {
        return View(environmentSettings.Value);
    }
}

查看/共享/组件/引导/ Default.cshtml

@model YourApp.Models.EnvironmentSettings
<script>
    System.import('app')
        .then(function (module) {
            module.main({
                other: "@Model.OtherSetting",
                loginUrl: "@Model.LoginUrl"
            })
        })
        .catch(function (err) {
            console.error(err);
        });
</script>

查看/共享/ _Layout.cshtml

<head>
...
@await Component.InvokeAsync("Bootstrap")
</head>

main.ts

export function main(settings: any) {
    platformBrowserDynamic([{ provide: 'EnvironmentSettings', useValue: settings }]).bootstrapModule(AppModule);
}