从 Electron 接收 ipcRenderer.on 后,Angular 2 View 未更新

标签 angular ipc settimeout electron

我正在使用 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/

相关文章:

javascript - setTimeout刷新和毫秒参数不起作用

javascript - setTimeout 在 "change"事件处理程序中,但仅适用于不同的调用者

angular 2 ionic 2处理按键事件

javascript - Angular - 返回 API 响应作为 promise

Angular "Must be imported or local"错误

c - 将共享内存与矩阵一起使用

c++ - 附加进程时 boost 删除 managed_shared_memory

javascript - 执行后,window.setTimeout() 抛出 'Uncaught TypeError: undefined is not a function' ?

angular - 如何定义 Angular Material 2 中的高度?

java - 进程输出是否以 EOF 结尾,如果是,如何删除?