I am writing a program that reads from a .csv file, cast the information into an interfaces and then pushes each interface into an array.
When initializing the array, everything is correct and logging the array gives me expected results. The problem is the array is either empty or undefined when called later.
import { Injectable } from '@angular/core';
@Injectable()
export class CSVService {
public csv: any;
public allPlayers: Player[];
public text: string;
public player: Player;
constructor() {
this.readFile();
}
public readFile(){
let rawFile = new XMLHttpRequest();
rawFile.open("GET", "../../data.csv", true);
this.splitCSV(rawFile);
rawFile.send(null);
}
public splitCSV(rawFile){
rawFile.onreadystatechange = function(){
if(rawFile.status === 200){
let allTextLines = rawFile.responseText.split(/\r\n|\n/);
allTextLines.shift();
var persons: Array<Player> = [];
for(let item of allTextLines){
var person = [];
person = item.split(',');
this.player = {
name: person[0],
serve_accuracy: +person[1],
serve_spin: +person[2],
return_skill: +person[3],
return_accuracy: +person[4],
return_spin: +person[5],
notes: person[6]
}
persons.push(this.player);
}
persons.pop();
}
this.allPlayers = persons;
console.log(this.allPlayers);
}
}
public status(){
console.log(this.allPlayers);
}
}
export interface Player {
name: string,
serve_accuracy: number,
serve_spin: number,
return_skill: number,
return_accuracy: number,
return_spin: number,
notes: string,
}
If I call the status method later in the program, I am given and undefined.
statusafter the operation is done? As you're doing it using http it's async so if you call it before the request is done then it might explain what you're getting. If that's not the case, then try to do:console.log(this, this.allPlayers);in yourstatusmethod and check what it prints forthis