【发布时间】: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