【问题标题】:Passing asp.net server parameters to Angular 2 app将 asp.net 服务器参数传递给 Angular 2 应用程序
【发布时间】:2016-09-17 03:47:31
【问题描述】:

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

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

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

有什么方法可以将服务器参数传递给 Angular 2 应用程序?

即我想使用 MVC 对象“HttpContext.User.Identity.Name”并将其注入到我的 Angular 2 应用程序的任何位置。

在 Angular 1 中,这可以使用 ng ".constant" 并将 .Net 对象序列化为 index.cshtml 中的 JSON。

看起来有一种方法可以传递参数,但这不适用于 .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) {

    }

}

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 知道如何在 RC5 之后做到这一点吗? ngModule 给我的参数带来了很多问题。
    • 这在 @Angular RC6 中不起作用。 @angular/core 不再支持“提供”。请任何解决方法
    • 感谢您的提示,但我可以在哪里找到“引导”和“提供”?
    • @amorel 我更新了我对 Angular 最新版本的回答……希望它对你有所帮助 ;-)
    • 有什么方法可以在不使用 systemjs 的情况下实现这一点?
    【解决方案2】:

    对于 .NET Core 服务器,我建议使用 IOptions&lt;&gt;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);
        }
    }
    

    Views/Shared/Components/Bootstrap/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>
    

    Views/Shared/_Layout.cshtml

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

    main.ts

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

    【讨论】:

      【解决方案3】:

      感谢您提供信息,感谢那些使用 platformBrowserDynamic 启动的用户:

      main.ts:

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

      【讨论】:

        猜你喜欢
        • 2023-03-22
        • 1970-01-01
        • 2017-06-10
        • 1970-01-01
        • 1970-01-01
        • 2017-06-20
        • 2017-05-25
        • 1970-01-01
        相关资源
        最近更新 更多