我正在使用 ipcRenderer 从我的 main.js 中的浏览器对话框中检索文件夹路径。
但由于某种原因,它不会更新我 View 中的文本字符串。
我知道为了让它工作,我需要做一个 setTimeout 来更新(感谢谷歌!)。但由于某种原因,这不起作用。
我使用的代码如下。
import { Component, OnInit } from '@angular/core';
declare var electron: any;
@Component({
selector: 'my-app',
template:
//added (click)="debug()" in order to update the {{path}} manually
`<h1 (click)="debug()">My First Angular 2 App with Electron</h1>
<br />Project Path: {{[(path)]}}
<button (click)="btnClick()">Select project path</button>
<br /> <br />`
})
export class AppComponent implements OnInit {
ipc:any;
path:string;
constructor(){
this.path = __dirname;
}
ngOnInit(){
electron.ipcRenderer.on('project-path-reply', (event, arg) => {
setTimeout(() => {
this.path = arg.return[0];
console.log('updated')
})
})
}
btnClick(){
electron.ipcRenderer.send('project-path',1);
}
debug(){
console.log(this.path);
}
}
有人能指出我正确的方向吗这是我第一个使用 Electron 的应用程序。
亲切的问候,
泰沃
最佳答案
对于这种情况,请使用 NgZone
import { Component,NgZone } from '@angular/core';
现在,在 .run()
中更新您的应用程序功能由 NgZone
提供constructor(zone:NgZone) {
ipcRenderer.on('project-path-reply', (event, arg) => {
this.zone.run(()=>{
// the code that requires change detection here, just like below //
this.path = arg.return[0];
console.log('updated')
});
});
}这很可能是因为 Electron 正在更新 Angular 变化检测区域之外的值。
关于从 Electron 接收 ipcRenderer.on 后,Angular 2 View 未更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43791398/