我有一个ipcMain和ipcRenderer进程(电子侧和角侧)。如何重写代码以异步接收来自主进程的数据?使用typeorm连接到数据库
渲染器一侧(data.service.ts):
constructor(private _electronService: ElectronService) {}
getItems(): Observable<Item[]> {
return of(this._electronService.ipcRenderer.sendSync('get-items')).pipe(
catchError((error: any) => Observable.throw(error.json))
);
}
app.component.ts
@Component({
selector: 'App',
template: `<div style="text-align:center">
<h1>
Welcome to {{ title }}!
</h1>
<h2>Here is the contents of the database: </h2>
<div>
<ul style="list-style: none">
<li *ngFor="let item of itemList">
{{ item.name }}
</li>
</ul>
</div>
</div>`
})
export class AppComponent implements OnInit {
itemList: Item[];
constructor(private appservice: AppService) {}
ngOnInit(): void {
console.log('component initialized');
this.appservice.getItems().subscribe((items) => (this.itemList = items));
}
主要方面(index.ts):
import { app, BrowserWindow, ipcMain } from 'electron';
import { createConnection } from 'typeorm';
import { Item} from './assets/model/item.schema';
const createWindow = async () => {
const connection = await createConnection({
type: 'mssql',
host: 'server\\instance',
username: 'sa',
password: 'password',
port: 1433,
database: 'test',
synchronize: true,
logging: true,
entities: [ Item ],
});
const itemRepo = connection.getRepository(Item);
ipcMain.on('get-items', async (event: any, ...args: any[]) => {
try {
event.returnValue = await itemRepo.find();
} catch (err) {
throw err;
}
});
答案 0 :(得分:1)
这对我有用:
data.service.ts(角度)
import { Injectable } from '@angular/core';
import { IpcRenderer } from 'electron';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class DataService {
private ipc: IpcRenderer;
constructor() {
if ((<any>window).require) {
try {
this.ipc = (<any>window).require('electron').ipcRenderer
} catch (error) {
throw error;
}
} else {
console.warn('Could not load electron ipc');
}
}
getData() {
return new Observable<any>(observer => {
this.ipc.once('getDataResponse', (event, arg) => {
observer.next(arg);
});
this.ipc.send('getData');
});
}
}
main.ts(电子)
import { app, BrowserWindow, ipcMain } from 'electron';
import * as path from 'path';
import * as url from 'url';
let win: BrowserWindow;
app.on('ready', createWindow)
app.on('activate', () => {
if (win === null) {
createWindow();
}
});
function createWindow() {
win = new BrowserWindow({
width: 800,
height: 600,
frame: false,
webPreferences: {
nodeIntegration: true // <-- important
}
});
win.loadURL(
url.format({
pathname: path.join(__dirname, `/../../dist/myApp/index.html`),
protocol: 'file:',
slashes: true,
})
);
win.webContents.openDevTools();
win.on('closed', () => {
win = null;
});
}
ipcMain.on('getData', (event, args) => {
event.reply('getDataResponse', {
data: [
{
name: 'test'
}
]
});
});