【问题标题】:How to bring Angular2's NgZone into a class without typescript?如何将 Angular2 的 NgZone 带入没有打字稿的课程?
【发布时间】:2016-04-08 21:50:53
【问题描述】:

我正在尝试在一个小项目中使用 NgZone,但不知道如何将其引入。angular.io 的文档说它们用于 javascript,但似乎使用 typescript。

Angular2 docs on NgZone

我发现的每个示例似乎都与文档一致,即打字稿:

Plnkr example of NgZone

export class NgZoneDemo {
  progress: number = 0;
  label: string;

  constructor(private _ngZone: NgZone) {}

我们没有使用打字稿,我不知道如何将 NgZone 带入我的课堂以挽救我的生命。我必须在 plunkr 中进行哪些更改才能使其在不使用 typescript 的项目中可用?

【问题讨论】:

    标签: javascript angular


    【解决方案1】:

    您可以使用ng.core.NgZone 对象并注入到您的组件中,如下所述:

    var Cmp = ng.core.
      Component({
        selector: 'cmp'
      }).
      View({
        template: '<div>Test</div>'
      }).
      Class({
        constructor: [ng.core.NgZone, function(zone) {
          // Use the zone
        }]
      });
    

    希望对你有帮助 蒂埃里

    【讨论】:

    • 在示例中使用 zone.run() 是不必要的,因为它将代码带回了 Angular 2 框架(它已经存在)。要显示zone.run() 的功能,您必须先使用zone.runOutsideAngular() 离开Angular 的NgZone,然后才能使用zone.run() 重新进入。
    • 问题只是关于如何将NgZone 注入构造函数而不是如何使用它......不是吗?
    • 否则我同意你的看法;-)
    • 我觉得标题太宽了。如果你看一下问题的内容,就更清楚了:“我正在尝试在一个小项目中使用 NgZone,但不知道如何引入它”和“我不知道如何将 NgZone 引入我的类”...
    【解决方案2】:

    发现将 Ngzone 传递给构造函数之前必须有一个静态参数数组,列出要传递的参数。我昨晚试过这个,但没有意识到为什么或那个案例很重要。无论如何,一旦我这样做了,它现在就可以在构造函数中使用了。

    export class NgZoneDemo {
      progress: number = 0;
      label: string;
    
      static parameters = [NgZone];
      constructor(ngZone) {
         // use here
      }
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-23
      • 2017-09-12
      • 2016-08-08
      • 1970-01-01
      • 2017-03-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多