Angular&电子 - 主与通信之间的IPC通信渲染过程

时间:2018-04-10 17:48:05

标签: angular electron

有小型号:

export class SettingsModel {
  DbFileName: string;
}

主要流程:

ipcMain.on('getSettings', function(event) {
    event.sender.send('resultSettings', 'Test settings');
});

IpcService:

import { Injectable } from '@angular/core';
import { ElectronService } from 'ngx-electron';

@Injectable()
export class IpcService {
  constructor(private _electronService: ElectronService) {}

  public on(channel: string, listener: Function): void {
    this._electronService.ipcRenderer.on(channel, listener);
  }

  public send(channel: string, ...args): void {
    this._electronService.ipcRenderer.send(channel, args);
  }
}

最后是角度分量:

export class SettingsComponent {
  constructor(private _electronService: ElectronService, private _db: DbService, private _ipc: IpcService) {
    this.Settings = new SettingsModel();
    console.log("1:" + this.Settings)
    _ipc.send('getSettings');
    console.log("2:" + this.Settings)
    _ipc.on('resultSettings', this._updateSettings);
    console.log("3:" + this.Settings)
  }

  private _updateSettings(evt: any, result: string) {
    console.log("4:" + result);
    console.log("5:" + this.Settings);
    this.Settings.DbFileName = result;
  }

  Settings: SettingsModel;
}

结果铬日志:

1:[object Object]
2:[object Object]
3:[object Object]
4:Test settings
5:undefined
Uncaught TypeError: Cannot set property 'DbFileName' of undefined

似乎IPC工作正常,但出于某种原因,当我得到响应时,我有一个不同的SettingsComponent类实例。我不知道为什么以及如何管理它。有什么想法或建议吗?

1 个答案:

答案 0 :(得分:1)

看起来问题既不是角度也不是电子,也不是IPC,而是使用TypeScript。

public on(channel: string, listener: Function): void {
  this._electronService.ipcRenderer.on(channel, listener);
}

我必须使用箭头表达式=>

public on(channel: string, listener: Function): void {
  this._electronService.ipcRenderer.on(channel, (evt, args) => listener(evt, arg));
}

_ipc.on('resultSettings', (evt, args) => this._updateSettings(evt, args));