================================================================
EDIT : SOLUTION After upgrading to 2.0 Final - Passing server parameters to ngModule after RC5 upgra
With a .NET Core server, I recommend to use a the IOptions<>
and a 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();
}
Models/EnvironmentSettings.cs
public class EnvironmentSettings
{
public string OtherSetting { get; set; }
public string LoginUrl { get; set; }
}
appsettings.json
{
"client": {
"LoginUrl": "http://localhost:45290/Token"
}
}
Controllers/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);
}
}
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);
}
An option would be to add a method in the module you import. So you can then call it to provide the object you want.
Here is a sample of the app/main
module:
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 })
]);
}
Then you can import it from your HTML main page like this:
<script>
System.import('app/main').then((module) => {
module.main({
userIdentityName: 'something from asp.net'
});
});
</script>
Update
With latest versions of Angular, you need to leverage modules this way:
export const USER_IDENTITY_NAME_TOKEN =
new InjectionToken('userIdentityName');
@NgModule({
(...)
providers: [
{
provide: USER_IDENTITY_NAME_TOKEN,
useValue: userIdentityName
}
]
})
export class MainModule() { }
thanks for info, for those using platformBrowserDynamic to boot:
main.ts:
//platformBrowserDynamic().bootstrapModule(asstModule);
export function main(appSettings: any) {
platformBrowserDynamic([{ provide: 'AppSettings', useValue: appSettings }]).bootstrapModule(asstModule);
}