角度2变化检测随着电子发生故障 [英] Angular 2 Change Detection Breaks Down with Electron

查看:77
本文介绍了角度2变化检测随着电子发生故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用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处理程序在有角区域外执行而导致的.因此,它不会对您的click事件做出反应,因为您离开了负责更改检测的区域.

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

希望这对您有帮助!

这篇关于角度2变化检测随着电子发生故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆