Angular2接口数组在初始化时定义,之后定义为undefined

时间:2016-07-26 14:28:25

标签: typescript angular

我正在编写一个从.csv文件读取的程序,将信息转换为接口,然后将每个接口推送到一个数组中。

初始化数组时,一切都正确,记录数组会给我预期的结果。问题是稍后调用时数组是空的还是未定义的。

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

如果我稍后在程序中调用状态方法,则会给出并且未定义。

1 个答案:

答案 0 :(得分:1)

只需将您的rawFile.onreadystatechange = function(){...}替换为箭头功能rawFile.onreadystatechange = () => {...},行this.player = ...将引用您的服务实例。这是一个问题