Angular 2 变化检测因 Electron 而崩溃

Angular 2 Change Detection Breaks Down with Electron

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

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

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

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

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 ) {}

希望对您有所帮助!