Angular 2 Change Detection Breaks Down with Electron

梦想的初衷 提交于 2019-11-28 07:47:33

问题


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

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.


回答1:


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

and then you can get rid of this.changeDetector.detectChanges();

With zone.run(...) you explicitely make code execute inside Angulars zone and change detection is run afterwards.

One more advice:

I noticed reduntant code in your app.component.ts like:

private service: Service;

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

You can just rewrite it like:

constructor(private service: Service ) {}

Hope this helps you!



来源:https://stackoverflow.com/questions/41254904/angular-2-change-detection-breaks-down-with-electron

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!