The function encounters an undefined array when called, despite the array being defined outside of the

Encountering an issue where an array I initiate is suddenly undefined within a function.

Here is the code snippet:

import { Component, OnInit } from '@angular/core';
import { text } from '@angular/core/src/render3';
import{SheetModel} from './models/sheetModel';
import { ThrowStmt } from '@angular/compiler';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  title = 'AngularCSVTest';
  csvContent: string;
  detailItems:SheetModel[]=[];


  ngOnInit(){
  }

  onFileLoad(fileLoadedEvent)
  {
    //this.detailItems=[];
    const textFromFileLoaded=fileLoadedEvent.target.result;
    this.csvContent=textFromFileLoaded;
    var rows=this.csvContent.split('\n');


    for(var i:number=0;i<rows.length;i++)
    {
      var item=new SheetModel();
      var rowItems:string[];
      rowItems=rows[i].split(",");
      item.index=i+1;
      item.Make=rowItems[0];
      item.Model=rowItems[1];
      item.Colour=rowItems[2];

      this.detailItems.push(item);
    }

    this.detailItems = this.detailItems.slice();
  }

  onFileSelect(input: HTMLInputElement) {
    const files=input.files;
    var content=this.csvContent;
    if(files && files.length)
    {
      const fileToRead=files[0];
      const fileReader=new FileReader();
      fileReader.onload=this.onFileLoad;
      fileReader.readAsText(fileToRead,"UTF-8");

    }
  }
}

Upon analysis, it seems that initializing the array at the beginning of the class results in it being undefined when attempting to push values to it within the onFileLoad function. One workaround could be initializing the array within the function, but this may lead to the array not updating in the view...

Seeking guidance on resolving this issue. Any insights are appreciated.

Answer №1

It is important to establish the context in which a function will be invoked.

Consider trying:

  onFileSelect(input: HTMLInputElement) {
    const files = input.files;
    var content = this.csvContent;
    if (files && files.length) {
      const fileToRead = files[0];
      const fileReader = new FileReader();
      fileReader.onload = this.onFileLoad.bind(this);  // <---- give this a shot
      fileReader.readAsText(fileToRead, "UTF-8");

    }
  }

Once the this context is defined, you can pass the event variable as well using bind(this, EVENT).

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

Implement a delay for a specific function and try again if the delay expires

In my TypeScript code, I am utilizing two fetch calls - one to retrieve an access token and the other to make the actual API call. I am looking to implement a 1-second timeout for the second API call. In the event of a timeout, a retry should be attempted ...

Secure mustache templates for data validation

Is there a method to achieve the following?: my-custom-template.mstach Hello {{name}}! script.js import { readFileSync, writeFileSync } from 'fs'; import * as Mustache from 'mustache'; export interface Person { name: string; } ...

Having trouble organizing a list of objects based on changing keys

Below is the implementation of a custom pipe designed to sort records: import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'sortpipe' }) export class SortPipe implements PipeTransform { transfor ...

Is it possible to integrate Firebase Storage into a TypeScript/HTML/CSS project without the use of Angular or React?

For my project, I am aiming to create a login and register page using TypeScript. Currently, my code is functioning well even without a database. However, I would like to implement Firebase for storing user credentials so that the login process becomes mor ...

Enhancing EventTarget in TypeScript (Angular 2+) for ES5 compilation

Is there a way to create a custom class that extends the EventTarget DOM API class? Let's say we have the following class: class MyClass extends EventTarget { constructor() { super(); } private triggerEvent() { this.dispatchE ...

Tips for selecting specific types from a list using generic types in TypeScript

Can anyone assist me in creating a function that retrieves all instances of a specified type from a list of candidates, each of which is derived from a shared parent class? For example, I attempted the following code: class A { p ...

Downloading videos from WebRTC getDisplayMedia in Angular 8 is not supported

Currently utilizing the NPM package in conjunction with Angular 8 found here: [ https://www.npmjs.com/package/webrtc-adapter ] to mimic the WebRTC getDisplayMedia functionality showcased here: [ ] I have successfully managed to initiate and terminate a r ...

Developing an npm library with ReactJs: A step-by-step guide

As a newcomer to React, I am eager to create my own npm library in ReactJS. Taking inspiration from my existing React project, the goal is to transform it into a package (or library) that can be easily integrated into other projects. This means allowing ...

Exploring the benefits of event subscription nesting

One feature I'm currently utilizing is the Angular dragula drag and drop functionality, which enables me to effortlessly move around Bootstrap cards within the view. When an item is "dropped," it triggers the this.dragulaService.drop.subscribe() funct ...

Implementing React custom component with conditional typing

My goal is to enable other developers to set a click handler for a button only if the button's type is set to button. Users can only set the type to either button or submit. I want to restrict developers from setting the onClick property on the comp ...

Encountered difficulties when trying to incorporate SCSS into my rollup build

Desired Outcome I aim to develop a small library for personal use, focusing on separating code into library (product) and application (project) code. All my source code resides in the /src folder, consisting of React, TypeScript, and SCSS code. I would l ...

Issue: Map container not located when implementing a leaflet map with Angular

Here is the complete error message: core.js:6479 ERROR Error: Map container not found. at NewClass._initContainer (leaflet-src.js:4066) at NewClass.initialize (leaflet-src.js:3099) at new NewClass (leaflet-src.js:296) at Object.createMap [a ...

Incorporating a React Bootstrap spinner into your project

I am looking to enhance my modal by adding a spinner to it. Here is the current structure of my modal: <Modal show={modal.show} onHide={onHideModal}> <form onSubmit={onImport}> <Modal.Header closeButton> <Mo ...

Can someone guide me on how to make a Carousel responsive using Angular?

HTML: <div class="voxel-row"> <div class="voxel-col-4"><h2 id="vagas_recentes">vagas recentes</h2></div> </div> <div id="carouselExampleControls" cl ...

Implementing Material Design in React using TypeScript

I'm currently in search of a method to implement react material design with typescript, but I've encountered some challenges. It appears that using export defaults may not be the best practice due to constraints in my tsconfig. Is there an al ...

Navigating Tabs in Angular 4 with ngx-bootstrap and the Router

I am facing an issue with my tab navigation using the router. Only clicking directly on the link switches the tab and updates the route. However, if you click around or below the link, the tab switches but the route does not update. It seems like the issue ...

Guide to implementing validation in an angular 2 dropdown using the Model-driven Approach

When the user clicks the submit button, the dropdown validation does not occur. I want the form to be validated if the user does not select any value, and in that case, the form state should be invalid. In my scenario, I have disabled the submit button whe ...

Is it possible to assign a variable in typescript using the interface as its type?

Here's the snippet of code I have written interface apiResult { Token: string; Result: any; } const result: apiResult = payload.Result; I am wondering about the significance of this code. Is it possible to assign a type from an interface to ...

I'm looking for a way to send a value to my component when the onBlur event is triggered on a PrimeNG autocomplete textbox. Any

I'm currently utilizing the PrimeNG autocomplete textbox. How can I pass a value to my component on the onBlur event? Template <p-autoComplete (ngModelChange)="orguser.userid = $target.value" class="ui-autocomplete autocomplete" [suggestions]="r ...

`How to cleverly fake dependencies with symbols in Jest, Vue3, and Typescript?`

I am faced with the following scenario: // symbols.ts - Injection Key defined as a Symbol export const FAQ_SERVICE: InjectionKey<FAQService> = Symbol('FAQService'); // main.ts - globally provides a service using the injection key app.provi ...