问题
There are small model:
export class SettingsModel {
DbFileName: string;
}
Main process:
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);
}
}
And finally angular component:
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;
}
Result chromium log:
1:[object Object]
2:[object Object]
3:[object Object]
4:Test settings
5:undefined
Uncaught TypeError: Cannot set property 'DbFileName' of undefined
It seems that IPC works fine, but for some reason when I get the response I have a different instance of the SettingsComponent class. I don't know why and how to manage it. Any ideas or suggestions?
回答1:
It looks like the problem is related with neither angular nor electon nor IPC, but with TypeScript.
public on(channel: string, listener: Function): void {
this._electronService.ipcRenderer.on(channel, listener);
}
I have to use arrow expression =>
:
public on(channel: string, listener: Function): void {
this._electronService.ipcRenderer.on(channel, (evt, args) => listener(evt, arg));
}
and
_ipc.on('resultSettings', (evt, args) => this._updateSettings(evt, args));
来源:https://stackoverflow.com/questions/49760019/angular-electron-ipc-communication-between-main-render-processes