【问题标题】:Angular 2 Change Detection Breaks Down with ElectronAngular 2 变化检测因电子而崩溃
【发布时间】:2017-05-06 09:53:38
【问题描述】:

我有一个使用 Angular 2 的 Electron 应用程序。该应用程序运行良好,直到使用 ipcRenderer 从本地 JSON 文件加载数据。然后,作用于服务中数据的按钮不再触发更改检测过程来更新视图。我创建了一个简化的示例应用程序来演示这里的问题: https://github.com/marshmellow1328/electron-angular-change-detection

我不知道为什么按钮停止触发本机更改检测。必须添加 ChangeDetectorRef 似乎没有必要。如果是,我想了解原因。

【问题讨论】:

  • 单击“什么都不做”是否会将视图刷新到有效状态?

标签: angular electron angular2-changedetection


【解决方案1】:

我调查了您的问题并确定它的发生是因为readFile 处理程序在角度区域之外执行。因此,它不会对您的点击事件做出反应,因为您离开了负责更改检测的区域。

对此最简单的解决方案是什么?

app.component.ts

constructor(private zone: NgZone) {
...
this.zone.run(() => {
  data.values.forEach(( value ) => { this.service.addValue( value ); } );
});

然后你就可以摆脱this.changeDetector.detectChanges();

使用zone.run(...),您可以明确地让代码在 Angulars 区域内执行,然后运行更改检测。

还有一条建议:

我注意到您的 app.component.ts 中有冗余代码,例如:

private service: Service;

constructor(service: Service ) {
    this.service = service;
}

你可以像这样重写它:

constructor(private service: Service ) {}

希望对您有所帮助!

【讨论】:

  • 所以我的印象是区域(和更改检测)在事件(单击按钮)而不是数据上运行。这表明并非如此。你知道吗?
  • Zone 不修补 ipcRenderer.on( 'load'fs.readFile 事件,因此 Zone.current 是 区域。当您运行cd.detectChanges() angular2 时,将在<root> 区域中运行更改检测,并且您的点击事件将添加到<root> 区域take.ms/uCa9h
  • 那你可以看看这篇入门书docs.google.com/document/d/…When async work gets scheduled, the callback function will execute in the same zone as the zone which existed at the time of invoking the async API.
  • 这就是为什么您的 removeValue 处理程序对更改检测没有影响。它现在在 区域中执行。
  • 感谢您的解释。这肯定有助于解释为什么它不起作用。
猜你喜欢
  • 2015-01-15
  • 2017-05-04
  • 2017-02-09
  • 1970-01-01
  • 1970-01-01
  • 2018-07-10
  • 2014-08-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多