将Page / Global Variables传递到Angular2应用程序以与服务一起使用

时间:2016-02-05 02:02:42

标签: typescript angular angular2-services

我正在寻找一些最好的做法。我的angular2应用程序将存在于现有的内容管理系统中。因此,我需要捕获此CMS生成的一些“变量”(如auth令牌等),并将其与我的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);
        };
    }

}

一个问题是typescript编译器抛出错误,它找不到“$”等。我可以通过在typescript类声明之前使用declare来强制执行此操作,如下所示:

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

3 个答案:

答案 0 :(得分:8)

更新&gt; = RC.6

在RC.6中添加了@NgModule()个提供程序,而不是在boostrap(...). Also中添加了for()`而不赞成使用对象文字语法:

在共享库中定义

import {OpaqueToken} from '@angular/core';

export let SF = new OpaqueToken('sf');
@NgModule({
  providers: [{provide: SF, useValue: $.ServicesFramework(moduleId)},
  directives: [...]
  ...
})
class SomeModule {}

也可以将提供商添加到组件和指令

@Component({
   providers: [
    {provide: SF, useValue: $.ServicesFramework(moduleId)},
   ]);
})
class SomeComponent {}

将其注入组件,指令,管道或服务,如

constructor(@Inject(SF) private sf:string) {}

<强>原始

在共享库中定义

import {OpaqueToken} from '@angular/core';

export let SF = new OpaqueToken('sf');

bootstrap()添加

// import SF from shared library

bootstrap(AppComponent, [
    // other providers
    provide(SF, {useValue: $.ServicesFramework(moduleId)}),
    ]);

<击> 你想用它的地方

// import SF from shared library

 constructor(@Inject(SF) private _sf: string){ }

这利用了Angulars DI并避免了硬编码的依赖性,这使得代码难以测试。

另见

<强>提示: 也可以使用普通字符串而不是OpaqueToken。使用OpaqueToken可防止名称冲突,例如,如果在许多用户使用的开源软件包中使用此名称冲突。如果您控制整个环境,那么您可以确保不会发生冲突,并且使用字符串而不是OpaqueToken应该是安全的。

更新

引入了通用支持的

InjectionToken来替换现已弃用的OpaqueToken

答案 1 :(得分:2)

为了扩展Gunther的答案,我也在RC5中做了这个,除了不是在bootstrap()(从以前的版本)中将它添加到提供者,你将令牌作为提供者放在新的正在做bootstrapping的@ngModule装饰器。例如:

@NgModule({
    bootstrap: [MyComponent],
    declarations: [MyComponent],
    imports: [BrowserModule],
    providers: [
        { provide: OpaqueToken, useValue: someObject }
    ]
})
export class AppModule { }

browserDynamicPlatform().bootstrapModule(AppModule);

答案 2 :(得分:0)

不确定这是否是最佳做法,但我遇到了同样的问题,我使用的解决方案(RC5就绪)如下:

步骤1)将您的设置类创建为@Injectable:

   import { Injectable }                                   from '@angular/core';

   @Injectable()

   export class MyAppSharedSettings {

        appName: string = "My Application Name";
        appTitle: string = "My Application Title";
        appVersion: string = "1.0.0.0 beta";
        welcomeMessage: string = "Welcome";
        userName: string = "";
   }

步骤2)在主模块上,如果您还没有这样做,请导入以下内容:

 //Imports required for NgModule directive
 import { NgModule }                          from '@angular/core';
 import { BrowserModule }                     from '@angular/platform-browser';
 import { HttpModule }                        from '@angular/http';

 //Imports required for your code to run
 import { MyAppMainComponent }               from './myapp.component';
 import { MyAppSharedSettings }              from './myapp.shared-settings';

步骤3)因此,您已将您的类标记为可注入(第一步),并使其可用(提供者)用于任何想要使用它的组件(步骤2)。现在,下一步就是将它放在组件的构造函数中。

 //Imports: Angular & Packages Related
 import { Component, Inject }            from '@angular/core';

 //You must import your injectable class in every component you plan to use it
 import { MyAppSharedSettings }          from '../../myapp.shared-settings';

 //defining how our component will be presented/used
 @Component({
     selector: 'my-content',
     templateUrl: './app/components/content/content.component.html',
     styleUrls: ['./app/components/content/content.component.css']
 })

 //here you name your variable as you please
 export class MyContent {
     yourVariableName: MyAppSharedSettings;

     constructor(private eafSettings: MyAppSharedSettings) {
         this.yourVariableName = eafSettings;
  }
 }

最后一步)以及我们如何在HTML中使用它:

 <h3 class="page-title">
     {{ yourVariableName.welcomeMessage }}<small> {{ yourVariableName.userName}}</small>
    </h3>
    <div class="row about-header">
        <div class="col-md-12">
            <h1>{{ yourVariableName.appName}}</h1>
            <h2>{{ yourVariableName.appTitle }}</h2>
            <a href="#platform"><button type="button" class="btn btn-danger uppercase">Start</button></a>
        </div>
    </div>
 </div>

希望它有所帮助。