gpt4 book ai didi

javascript - 如何在控制台日志之外获取IPC消息的值?

转载 作者:行者123 更新时间:2023-12-03 12:38:04 27 4
gpt4 key购买 nike

我正在使用 Electron 和 Angular 来开发一个应用程序,试图在其中发送一些本地存储在计算机上的信息。我能够在正确的时间成功地从 Electron 侧向 Angular 侧发送消息。但是,除了控制台日志中的其他地方,我无法访问该消息。
file.service.ts:

import { Injectable } from '@angular/core';
import { IpcRenderer } from 'electron';

@Injectable({
providedIn: 'root'
})
export class FileService {
private ipc: IpcRenderer | undefined;
private filePath: string[];
constructor() {
if (window.require) {
try {
this.ipc = window.require('electron').ipcRenderer;
} catch (error) {
throw error;
}
} else {
console.warn('Could not load electron ipc');
}
this.ipc.on('getFiles', (event, file) => {
this.filePath = file;
console.log('in service: ' + this.filePath); // correct
});
}

public getFilePaths(): string[] {
return this.filePath; // undefined
}
}
app.component.ts的一部分:
export class AppComponent implements OnInit{
constructor(private formBuilder: FormBuilder, private fileService: FileService) {
}
ngOnInit(): void {
const bob: string[] = this.fileService.getFilePaths();
console.log('in component: ' + bob); // undefined
}
我发现了另一种方法,但是我无法从 promise 中获得信息。
file.service.ts:
import { Injectable } from '@angular/core';
import { IpcRenderer } from 'electron';

@Injectable({
providedIn: 'root'
})
export class FileService {
private ipc: IpcRenderer | undefined;
constructor() {
if (window.require) {
try {
this.ipc = window.require('electron').ipcRenderer;
} catch (error) {
throw error;
}
} else {
console.warn('Could not load electron ipc');
}
}

async getFiles(): Promise<string[]> {
return new Promise<string[]>((resolve) => {
this.ipc.on('getFiles', (event, info) => {
resolve(info);
});
});
}
}
app.component.ts的一部分:
export class AppComponent implements OnInit{
constructor(private formBuilder: FormBuilder, private fileService: FileService) {
}
ngOnInit(): void {
this.fileService.getFiles().then(console.log); // works, but only way to access message
}
如果有一种方法可以通过任何一种方法或其他方法将消息放入string []变量中,我将不胜感激。

最佳答案

您可以使用第二种方法将异步方法解析为变量。
您可以尝试执行以下操作,看看是否可行吗?

export class AppComponent implements OnInit {
private myVariable: string[]

constructor(
private formBuilder: FormBuilder,
private fileService: FileService
) { }

async ngOnInit(): Promise<void> {
this.myVariable = await this.fileService.getFiles()
}
}

关于javascript - 如何在控制台日志之外获取IPC消息的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65570721/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com