【问题标题】:Bind methods on Zone callbacks from an external class绑定来自外部类的区域回调方法
【发布时间】:2016-11-03 09:39:44
【问题描述】:

上下文

我正在开始一个学生项目,它是 angular2 的度量工具。

我实际上正在研究概念证明,证明我可以在运行时仅使用静态注册方法 myLibClass.registerComponents([Component1, Component2,...]) 获得组件的指标,该方法将具有类似这样的实现(伪代码):

registerComponents(components:any[]):void{
    components.forEach(component => {
        //Register metric methods on zone foreTask and afterTask
    });
}

问题

如何获取angular2的全局区?我想在 ng2 区域上绑定我的方法,以便能够检查每次调用的执行时间,而 NgZone 不提供执行此类操作的工具。

另一个从外部类度量组件的想法也是受欢迎的

更新:

我做了一些研究,发现如何使用 ̀ Zone.current` 获取全局 angular2 区域。

问题仍然存在,因为它的第二部分(最难的部分)尚未完成:

我想在 ng2 区域上绑定我的方法,以便能够检查每个调用的执行时间,而 NgZone 不提供执行此类操作的工具。

做到这一点的唯一方法是分叉 angular2 区域并将 angular 使用的实际区域替换为我的分叉区域(这是我看到的唯一方法)。

有可能吗?分叉区域不是问题,但我无法在 angular2 上连接它。

由于我需要比null 更多的信息(正如您在the source code of ngZone 上看到的那样,每个触发的事件都由null 触发,这不允许我获得我需要的关于最后一个微任务的信息,例如呼叫或呼叫者的名称),我需要有一个自定义区域,它将由 angular2 使用,但我无法扩展 NgZone,因为它没有使用 DI 进行实例化,因此 angular2 使用的区域仍将是 NgZone。

【问题讨论】:

  • 你有没有试过像class AppModule { constructor(private zone: NgZone) { (<any>window).ngZone = zone; } }这样暴露角区?
  • 您还可以使用Zone.current 获取角度的区域。我将编辑问题以添加我对该问题的进展。
  • Zone.current 仅当您在角度区域内调用它时才会成为角度区域
  • 是的,这就是我需要的,因为我的应用程序是一个 angular2 模块,它将注册组件以获取有关使用静态注册方法的指标。但如果我需要在 angular2 之外获取它,您的评论将对我有用:) 谢谢。
  • Forking the zone is not a problem but I can't connect it on angular2. - 看源代码github.com/angular/angular/blob/2.1.2/modules/%40angular/core/… 然后看这个答案stackoverflow.com/questions/39686305/… (_bootstrapModuleWithZone)

标签: angular zonejs


【解决方案1】:

如果您想使用覆盖的 ngZone 运行应用程序,您可以执行以下技巧。

const platform = platformBrowserDynamic();
const zone = new MyZone();
platform['_bootstrapModuleWithZone'](AppModule, [], zone);

在ng1升级适配器中使用

但不幸的是它是私有方法

另见

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-22
    • 2013-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多