将变量从Angular组件传递到窗口对象

时间:2017-12-04 11:08:33

标签: javascript angular

我正在开发一个Angular(v4)应用程序,并在此应用程序中构建了一个组件。我需要从此组件返回4个值并将它们附加到Javascript中的Window对象,以便可以在Optimizely中处理它们。我正在寻找一种简单快捷的方法来解决这个问题;这些是我想要处理的数字:

  public AmOfWinners: number      = 95682;
  public Week1: number            = 96253;
  public Week2: number            = 97551;
  public Week3: number            = 98247;

这是我的组成部分:

import {Component, NgModule} from '@angular/core';
import {downgradeComponent} from "@angular/upgrade/static";
import {Observable} from 'rxjs/Rx';

@Component({
  selector: 'stats-win',
  template: '<h3>+{{AmOfWinners}}</h3>',
  styles: ['h3 { color: #85AC07; }']

})
export class StatsWinComponent {

  public AmOfWinners: number      = 95682;
  public Week1: number            = 96253;
  public Week2: number            = 97551;
  public Week3: number            = 98247;

  constructor() {
    /* tslint:disable:typedef */
    Observable.interval(604800).subscribe(x => this.AmOfWinners = this.Week1);
    Observable.interval(604800).subscribe(x => this.AmOfWinners = this.Week2);
    Observable.interval(604800).subscribe(x => {
      this.AmOfWinners = this.Week3;
    });
    /* tslint:enable:typedef */
  }


}

@NgModule({
  declarations: [
    StatsWinComponent
  ],
   entryComponents: [
    StatsWinComponent
  ]
})
export class StatsWinModule {

  public static downgrade(app: ng.IModule): void {
    app.directive('statsWin', downgradeComponent({component: StatsWinComponent}) as ng.IDirectiveFactory);
  }
}

因此,我想访问DOM中的这些数字并从那里处理它们。最好的方法是什么?任何提示或帮助将非常感谢,谢谢!

1 个答案:

答案 0 :(得分:0)

您始终可以构建服务并共享。如果变量随条件而变化,则分配可观察的机制,例如“行为主体”。但最简单的方法是将变量分配给整个应用程序全局可用的window对象。您可以在组件'x'上分配window [x] ='y'并通过window.x

来利用'y'组件中的值。