我有一个使用 Angular 2 的 Electron 应用程序。该应用程序工作正常,直到使用 ipcRenderer 从本地 JSON 文件加载数据。然后,作用于服务中数据的按钮不再触发更改检测过程来更新 View 。我创建了一个简化的示例应用程序来演示这里的问题: https://github.com/marshmellow1328/electron-angular-change-detection
我不知道为什么按钮停止触发 native 更改检测。必须添加 ChangeDetectorRef 似乎没有必要。如果是,我想了解原因。
最佳答案
我调查了您的问题并确定它的发生是因为 readFile
处理程序在 Angular 区域之外执行。因此,它不会对您的点击事件使用react,因为您离开了负责更改检测的区域。
最简单的解决方案是什么?
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 ) {}
希望对你有帮助!
关于Angular 2 变化检测因 Electron 而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41254904/