2016-05-20 16 views
6

===================================== ===========================Passare i parametri del server asp.net all'app Angular 2

EDIT: SOLUZIONE Dopo l'aggiornamento a 2.0 Final - Passing server parameters to ngModule after RC5 upgrade

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

Un modo per passare i parametri del server a un'applicazione Angular 2?

Ad esempio, mi piacerebbe utilizzare l'oggetto MVC "HttpContext.User.Identity.Name" e averlo iniettato ovunque nella mia app angolare 2.

In 1 angolare ciò è stato possibile utilizzando ng ".constant" e serializzando gli oggetti .Net su JSON in index.cshtml.

Sembra che ci sia un modo per passare i parametri ma questo non funziona con il codice .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> 

SOLUZIONE FINALE: (grande grazie a Thierry)

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 
      ]); 
    } 

utilizzati:

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) { 

    } 

}

risposta

8

Un'opzione potrebbe essere quella di aggiungere un metodo nel modulo si importa. Quindi puoi chiamarlo per fornire l'oggetto che desideri.

Ecco un esempio del modulo 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 }) 
    ]); 
} 

Quindi è possibile importarlo dalla pagina principale HTML come questo:

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

Aggiornamento

con le ultime versioni di Angular, è necessario sfruttare i moduli in questo modo:

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

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

alcuna idea di come questo potrebbe essere fatto dopo RC5? ngModule mi sta dando molti problemi con i miei parametri. – vidalsasoon

+4

Questo non funziona in @Angular RC6. "fornire" non è più supportato in @ angular/core. Qualsiasi soluzione alternativa per favore –

+0

Grazie per i suggerimenti ma dove posso trovare "bootstrap" e "fornire" per favore? – amorel

4

Grazie per le informazioni, per coloro che utilizzano platformBrowserDynamic per l'avvio:

main.ts:

//platformBrowserDynamic().bootstrapModule(asstModule); 

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

0

Con un server .NET Nucleo, vi consiglio di usare un l'IOptions<> e un 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(); 
} 

Modelli/Impostazioni ambiente.cs

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

appsettings.json

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

Controller/components/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); 
    } 
} 

Vista/Shared/Componenti/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> 

Visite/shared/_Layout.cshtml

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

main.ts

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