=================================================== =============
编辑:解决方案升级到 2.0 Final 后 -RC5升级后将服务器参数传递给ngModule https://stackoverflow.com/questions/38948463/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 代码。在 Angular 2 中定义全局常量 https://stackoverflow.com/questions/34986922/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>
最终解决方案:(非常感谢蒂埃里)
索引.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
]);
}
Usage:
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) {
}
}