Is there a way to access the value of an IPC message beyond just using console log?

I am developing an app using electron and angular where I need to send locally stored information from my computer. I have successfully managed to send a message from the electron side to the angular side at the right time. However, I am facing issues accessing the message anywhere other than in the console log.

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
  }
}

part of 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
}

I have discovered another method, but I'm unable to retrieve the message from the 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);
      });
    });
  }
}

part of app.component.ts:

export class AppComponent implements OnInit{
  constructor(private formBuilder: FormBuilder, private fileService: FileService) {
  }
  ngOnInit(): void {
    this.fileService.getFiles().then(console.log); 
}

If there is a way to extract the message into a string[] variable using either of these methods or a different approach, any assistance would be greatly appreciated.

Answer №1

A different approach to handling asynchronous methods is by assigning the result to a variable.

Why not give this method a try and see if it resolves your issue?

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()
  }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason that Jest is not able to spy on the function?

A custom Hook was developed with only one function being imported. Ensuring this function is called with the correct arguments is crucial. import { IsValueAlreadyRegistered } from "../../entities/registration/actions"; export const useForgetPass ...

Implementing a Push System without using node.JS

I am looking to develop a notification system similar to Facebook's, where notifications appear on the bottom-left side of the screen when someone interacts with your posts, for example. However, my challenge is that I need the server to send real-ti ...

Transform nested properties of an object into a new data type

I created a versatile function that recursively converts nested property values into numbers: type CastToNumber<T> = T extends string ? number : { [K in keyof T]: CastToNumber<T[K]> }; type StringMap = { [key: string]: any }; const castOb ...

Is it possible for me to use an NPX tool to execute git clone command?

I am currently working on developing a personalized NPX tool that will install my custom npm package onto a locally hosted server. At the moment, I have a layout template that I want other users to replicate when they run my NPX command. Here is an exampl ...

The issue of duplicated elements arises when Ajax is utilized within Django

Upon form submission, a Graph is generated using Plotly. Utilizing Ajax to submit the form without refreshing the page results in duplicating the form div on the screen. How can this issue be resolved? The code snippet below showcases my implementation wit ...

Angular controller unit testing is an essential practice in software development

I am currently working with an angular module named 'widgets'. In my app, I have used its signature as follows: var app = angular.module('widgets', [ 'widget.Panel', 'widget.List', 'services' ] ...

SecurityError: The dubious operation triggers CORS to persist in its insecurities

I have developed an HTTP server using Express in Node.js. This server is currently running locally on port 3000. There is a served HTML page called "index.html" which makes AJAX GET requests for contents (in HTML format). These AJAX contents are also serv ...

Filter an array using an algorithm inspired by Binary Search Trees

I am facing a challenge with a sorted array of dates, here is an example: let arr = ['2019-03-12', '2019-02-11', '2019-02-09', '2018-06-09', '2018-01-24', ..] The arr has a length of 100,000, and I need t ...

Trouble with selectionChange event in mat-select component in Angular 13

I'm having trouble getting the selectionChange event to fire in my mat-select when the value is changed. html file <mat-select (selectionChange)="changeCategory()"> <mat-option *ngFor="let category of categ ...

What's the process for creating a synchronous function in AngularJS?

Is there a way to make storyboard.getAdressTimeLine run synchronously? I need storyboard.drawTimeLine to continue executing only after storyboard.getAdressTimeLine is done for (var i = 0; i < response.data.length; i++) { var obj=response.data[i]; var d ...

Refresh Entity with Real-Time Data on Cesium

I have been attempting to showcase an entity moving within Cesium through the use of live/dynamic data. After trying various techniques and consulting past forums, particularly those from 2015-2016, I am still struggling to make it work. Despite my effort ...

I am currently struggling with the mapquest GeoJson integration within my Node/Express application. I keep encountering an error message that reads "body used already."

I attempted to utilize the mapquest API by following the provided documentation, however I encountered an error message: HttpError: body used already for: Below is my geoCoder.js configuration: const NodeGeocoder = require('node-geocoder'); con ...

Creating a Basic jQuery AJAX call

I've been struggling to make a simple jQuery AJAX script work, but unfortunately, I haven't had any success so far. Below is the code I've written in jQuery: $(document).ready(function(){ $('#doAjax').click(function(){ alert ...

Verify the value of the variable matches the key of the JavaScript object array and retrieve the corresponding value

array = { event: [{ key: "value", lbl: "value" }], event1: [{ key: "value", lbl: "value" }] var variable; if(variable in array){ //need to handle this case } I am looking for a function that takes the name of an ar ...

Code snippet for converting the current webpage into a PDF using Jquery

Looking for guidance on how to convert the current webpage into a PDF using client-side (JQuery) code. The PDF should include all content from the webpage along with a few images if possible. The main requirement is to have all webpage content in the PDF, ...

Troubleshooting Bootstrap 4 Modal in JavaScript and Vue: Uncaught ReferenceError: $ is not defined

I'm struggling to figure out how to trigger a Bootstrap 4 modal from my Vue 3 app using JavaScript. Whenever I try to launch the modal, I keep encountering this error message: $ is not defined at eval When looking for solutions, I noticed that most a ...

Tips for toggling the visibility of a <div> element using PHP code inside

I'm having trouble with a dropdown list that is supposed to show/hide some divs containing PHP files. However, when I try to toggle the visibility of the divs using the dropdown list, it doesn't seem to work as expected. Can anyone help me figure ...

Troubleshooting: Icon missing from React vscode-webview-ui-toolkit button

In the process of developing a VSCode extension using React and the WebUi Toolkit library for components, I encountered an issue with adding a "save" icon to my button. I diligently followed the documentation provided by Microsoft for integrating buttons i ...

Reverting Vue Draggable Components to Their Original Position Upon Dropping Them

In my Vue 3 project, I'm implementing vuedraggable to enable element reordering within an expansion panel. However, I've encountered an issue where the dragged elements revert to their original positions upon release. This behavior suggests that ...

New project was successfully generated, but the information is missing when transmitted from React to Django API

I recently developed a React + Django application and implemented a basic CRUD feature. Everything was working smoothly until I encountered an issue while creating a project and storing it in the Django database. When I view the project at projects/list, o ...