Is there a solution to successfully retrieving the value of res from the readCsv() method instead of it returning undefined?

In this scenario, I have a file uploader that accepts .json and .csv files. When the upload button is clicked, the HomeComponent calls the service dataparser which has two functions: readJson and readCsv. One function returns an observable while the other returns an array. Instead of handling these complexities at the component level, I want to return only the array of data on the HomeComponent page. However, I am facing issues with observables in the service.

**dataparser.service.ts has three methods**

async uploadDocument() {
const type = this.checkType();
if(!type) return;
 let m = type == "csv" ?  await this.readCsv() : await this.readJson();
 if(m){
  console.log(m);
  return m;
}
console.log(" m is empty");
} 

The readJson method returns an array of objects and m is not empty if the file type is json. It returns m to the caller function on HomeComponent.

private  readJson() {
    return new Promise((resolve,reject) =>{
      const fr: FileReader = new FileReader();
      fr.readAsText(this.file);
      fr.onerror = () =>{
        fr.abort();
        reject(new DOMException("Problem parsing input  file."));
      }
      fr.onload = () =>{
        resolve(JSON.parse(fr.result as string));  
      }})
  } 

The readCsv method returns an empty variable (res) due to the subscribe method. Is there any workaround to get the value of res from the readCsv function without subscribing? I do not want to handle these two results on the HomeComponent page.

private async readCsv() {
    let res: any[];
     this.ngxCsvParser.parse(this.file, { header: this.header, delimiter: ',' })
    .pipe().subscribe((result: Array<any>) => {
 
      // console.log('Result', result);
       res = result;
    }, (error: NgxCSVParserError) => {
      console.log('Error', error);
    });
    if(res)
    {
      console.log(" i got m");
      return res;
    } 
  }

Answer №1

While you cannot directly await Observables, you are able to utilize the await keyword with a Promise instead. One way to achieve this is by calling the .toPromise() method on the subscription of the Observable. Here's an example demonstrating this concept: const result = await observableSubscription.toPromise();

private async readCsvFile() {
    let data: any[];
   data = await this.csvParser.
     parse(this.file, { header: this.header, delimiter: ',' }).toPromise()
    if(data)
    {
      console.log("Data retrieved successfully!");
      return data;
    } 
  }   

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

How to display an image in a pop-up with a title

I am currently using the Bootstrap framework and I am trying to create a popup image with a title, but it only shows the image. I am not sure how to add code in JavaScript to display the title as well. Can someone please assist me? Here is my code: Javas ...

Issue with vue-template-compiler in Vue.js 3 webpack configuration

I am currently working on integrating vuejs 3 into a project that already utilizes webpack. I have been looking into using vue-loader as part of this process. After consulting the official documentation, I came across the following information: Every new ...

Locking mat-toolbar and mat-tabs to the top in Angular Material 2

As I work on my website, my goal is to fix the < Mat-Toolbar > at the top of the screen and then directly underneath that, lock the < Mat-Tabs >. The challenge I'm facing is that the position: fixed in CSS is not working as expected. When ...

Having trouble with Javascript/jQuery not functioning in IE8?

My current project involves a website that functions smoothly in Chrome, but encounters issues with running JavaScript/jQuery scripts in IE8. Even a simple alert on page load fails to execute. Admittedly, my approach is a bit messy as I have mixed CSS an ...

Retrieve relational data through search functionality in Laravel

My Laravel 5.6 project includes the following model code: public function getClassTreaner() { return $this->hasOne('App\User', 'id', 'class_treaner'); } public static function searchScoop($keyword) { $data = ...

Converting a string to a JSON array with Jackson in RESTful APIs

As I delve into the world of JSON and REST, I find myself testing a REST API that returns strings in the following format: [{ "Supervisor_UniqueName": "adavis", "Active": "true", "DefaultCurrency_UniqueName": "USD", "arches_type": "x-zensa ...

Angular Module without any components

The Angular modules documentation provides an example of a module that includes a template, a component, and a provider. This module is then imported into the root module and instantiated by using the element defined by the component like this: <app-co ...

The absence of a property map within String Flowtype has caused an issue

There is an issue with Flowtype when it comes to arrays. type Properties = { films?: Array<any> } render() { const { movies } = this.props; return ( <React.Fragment> <main className="moviedata-container"> { ...

React is throwing an error because it cannot access the property 'length' of an undefined value

TypeError: Cannot read property 'length' of undefined When I try to run my React app, I keep getting this error message from the compiler. What steps should I take to resolve this issue? request = (start,end) => { if(this.state.teams.lengt ...

What is the best way to position a container div over another container using Bootstrap or CSS?

https://i.sstatic.net/q1qGi.png I'm working on a Bootstrap 4 layout where container B needs to overlay part of container A. I want to achieve a design where container B appears on top of container A. Any suggestions or references on how to achieve th ...

When an array becomes empty, the interaction between v-for and v-if fails to function properly

Today I encountered a rather peculiar issue that I would like to share here: I noticed that when using v-for and v-if together with data value of [], it doesn't seem to work. For example: ts: [] <div v-for="t in ts" :key="t" v-if="ts.length"> ...

"Can Three.js be used with Web Workers? When I try to use importScripts("three.js"), it throws an error

When trying to importScripts("three.js"), an error is thrown: Uncaught ReferenceError: window is not defined: for ( var x = 0; x < vendors.length && !window.requestAnimationFrame; ++ x ) { Removing all references to the window object in thre ...

Issue Encountered When Integrating a StencilJS Component Library with NextJS

I have my own StencilJS component library hosted privately on GitLab. While I can successfully use it in regular HTML, I'm facing issues trying to integrate the StencilJS Web Components into a NextJS app. When attempting to do so, I encounter the fol ...

Steps to resolve the error message 'Argument of type 'number' is not assignable to parameter of type 'string | RegExp':

Is there a way to prevent users from using special symbols or having blank spaces without any characters in my form? I encountered an error when trying to implement this in my FormGroup Validator, which displayed the message 'Argument of type 'nu ...

A guide on obtaining the ReturnType within a UseQuery declaration

I am currently working on building a TypeScript wrapper for RTKQ queries that can be used generically. I have made progress on most of my goals, but I am encountering an issue with determining the return type for a generic or specific query. I have shared ...

What could be causing this JS file to not impact the DOM as expected?

Currently, I am delving into the world of JavaScript and trying to gain a better understanding of how to manipulate the DOM on my own. Throughout this learning process, I have encountered a puzzling situation that I am seeking assistance with. The followi ...

What could be the reason why the @media print selector is not showing the correct format when I try to print?

When I click the print button, the text is supposed to display in four columns in the print dialog, but it appears as paragraphs instead. This is my script code where there is a click event for the print button. When I click on it, the print dialog pop ...

Mastering the Art of Mocking ControlContainer in Angular Unit Testing

Is there a way to simulate a ControlContainer instance in order to effectively test my component? One of my child components incorporates a ControlContainer within the constructor, leading to usage like this: <acr-score-card formGroupName="score">& ...

Edit CSS attributes within Angular 2+ framework

When using jQuery, we have the ability to do the following: JQuery('.someStyle') .css({"background", "red"}) This allows us to directly change the CSS property in style. While working with Angular 2+, we can use [style.<property>] for ...

The canvas loop list is not displaying for the oscillating image effect

My concept originated when I attempted to create a wave effect using an array of images, but unfortunately, it did not work as expected. The goal was to generate multiple waves in the images by utilizing an array, however, the desired outcome was not achie ...