【发布时间】:2016-02-05 02:02:41
【问题描述】:
我在这里寻找一些最佳实践。我的 angular2 应用程序将存在于现有的内容管理系统中。因此,我需要捕获此 CMS 生成的一些“变量”(如身份验证令牌等),并将它们与我的 angular2 应用程序中的 http 请求一起使用。
当 CMS 显示 index.html 页面时,CMS 会对其进行预解析,并在页面发送到浏览器之前替换一些标记(即 [ModuleContext:ModuleId])。
这是我的 index.html 页面的示例(略):
<!-- 2. Capture CMS values to pass to app -->
<script type="text/javascript">
var moduleId = parseInt("[ModuleContext:ModuleId]");
var portalId = parseInt("[ModuleContext:PortalId]");
var sf = $.ServicesFramework(moduleId);
</script>
<!-- 3. Configure SystemJS and Bootstrap App-->
<script type="text/javascript">
System.config({
packages: {
//sets the root path of the Angular2 App
'DesktopModules/KrisisShifts/app': {
format: 'register',
defaultExtension: 'js'
}
},
map: { 'app': './app' }
});
System.import('app/boot')
.then(null, console.error.bind(console));
</script>
<shift-app>Loading...</shift-app>
特别是 $.ServicesFramework 用于生成有效的 http web.api 请求。我想在可以注入到每个使用它的组件中的服务中捕获它。
例如(我正在使用打字稿):
import {Injectable} from 'angular2/core';
import {OnInit} from 'angular2/core';
@Injectable()
export class dnnService implements OnInit{
sf: any;
constructor() {}
ngOnInit() {
if ($.ServicesFramework) {
this.sf = $.ServicesFramework(moduleId);
};
}
}
一个问题是打字稿编译器会抛出找不到“$”等错误。我可以通过在打字稿类声明之前使用声明来强制它工作,如下所示:
//Global Variable Declarations
declare var $: any;
declare var moduleId: any;
问题:
有什么更好的方法(如果存在)来捕获这些“全局”变量,以便在可以很好扩展的应用程序中使用。
编辑 - 更新到 RC6
我在 RC6 中使用了以下内容:
@NgModule({
declarations: [
AppComponent,
FormatDatePipe,
ShiftPartialPipe
],
imports: [
BrowserModule,
RouterModule.forRoot(AppRoutes),
FormsModule,
ReactiveFormsModule,
HttpModule
],
bootstrap: [AppComponent],
providers: [
{ provide: LocationStrategy, useClass: HashLocationStrategy },
{ provide: dnnModId, useValue: moduleId },
{ provide: dnnPortalId, useValue: portalId },
{ provide: dnnEditMode, useValue: editMode },
{ provide: dnnSF, useValue: $.ServicesFramework(moduleId) }
]
})
【问题讨论】:
-
您对
declare var ...或parseInt("[ModuleContext:ModuleId]")有疑问吗? -
它是关于最佳实践的。我展示的是工作,但我想知道其他人是否有更好的方法来完成同样的事情,主要是将全局或页面级别的 javascript 变量放入 angular2 服务(这样可以对其进行测试)
-
@JKing 你找到更好的方法了吗?我正在尝试使用新的 cli(使用 Webpack)定义一个标准,但我仍在努力……它也适用于相同的用例:DNN、http 标头等,理想情况下是自动模块 ID 检测跨度>
-
@iJungleBoy 我做到了。我不得不放弃 @inject 的做法。我今天不在电脑旁。我明天会发布它是如何工作的。
-
@JKing 你如何在客户端
var moduleId = parseInt("[ModuleContext:ModuleId]");中呈现服务变量,就像这样。我从昨天开始就想知道怎么做。我将变量存储在视图中,想在客户端使用此变量。
标签: typescript angular angular2-services