Angular 2 变化检测因电子而崩溃 [英] Angular 2 Change Detection Breaks Down with Electron
问题描述
我有一个使用 Angular 2 的 Electron 应用程序.该应用程序工作正常,直到使用 ipcRenderer 从本地 JSON 文件加载数据.然后,作用于服务中数据的按钮不再触发更改检测过程来更新视图.我创建了一个简化的示例应用程序来演示这里的问题:https://github.com/marshmellow1328/electron-angular-change-detection
I have an Electron app using Angular 2. The app works fine until a load data from a local JSON file using ipcRenderer. Then buttons which act on data in a service no longer trigger change detection process to update the view. I created a simplified example app which demonstrates the problem here: https://github.com/marshmellow1328/electron-angular-change-detection
我不知道为什么按钮停止触发本机更改检测.必须添加 ChangeDetectorRef 似乎没有必要.如果是,我想了解原因.
I have no clue why the button stops triggering the native change detection. Having to add ChangeDetectorRef seems like it shouldn't be necessary. If it is, I'd like to understand why.
推荐答案
我调查了您的问题并确定它发生是因为 readFile
处理程序在角度区域之外执行.因此,它不会对您的点击事件做出反应,因为您离开了负责更改检测的区域.
I investigated your issue and determined that it happens because readFile
handler is executed outside angular zone. So, it won't react on your click event because you left zone responsible for change detection.
对此最简单的解决方案是什么?
What's the easiest solution for that?
app.component.ts
constructor(private zone: NgZone) {
...
this.zone.run(() => {
data.values.forEach(( value ) => { this.service.addValue( value ); } );
});
然后你就可以摆脱 this.changeDetector.detectChanges();
使用 zone.run(...)
您可以明确地让代码在 Angulars 区域内执行,然后运行更改检测.
With zone.run(...)
you explicitely make code execute inside Angulars zone and change detection is run afterwards.
还有一条建议:
我注意到您的 app.component.ts
中有冗余代码,例如:
I noticed reduntant code in your app.component.ts
like:
private service: Service;
constructor(service: Service ) {
this.service = service;
}
你可以像这样重写它:
constructor(private service: Service ) {}
希望对您有所帮助!
这篇关于Angular 2 变化检测因电子而崩溃的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!