Angular load file.json并转换为对象类

时间:2018-04-30 20:29:36

标签: javascript json angular typescript angularfire

我的应用加载了用户' pc:

的file.json

app.component.html



  <div class="file btn btn-lg btn-primary">
    Upload
    <input type="file" class="upload" (change)="changeListener($event.target.files)">
  </div>
&#13;
&#13;
&#13;

在我的 app.component.ts

  user: User;
  userArray: Array<User>;
  fileList: Array<any>;

  ngOnInit() {
   this.user = new User();
   this.userArray= Array<User>();
   this.fileList= Array<any>();
  }

然后接收文件的方法:

  public changeListener(files: FileList) {
    if (files && files.length > 0) {
      let file: File = files.item(0);

      let reader: FileReader = new FileReader();
      reader.readAsText(file);
      reader.onload = (e) => {
        let loadFile: string = reader.result;
        JSON.stringify(loadFile)
        this.fileList = loadFile.split('\r\n');

    if (this.fileList.length > 0) {
      for (const i of this.fileList) {
        if (i !== null) {

          this.user = i; //--I THINK HERE IS MY PROBLEM--
          this.userArray.push(this.user); //----HERE IS UNDEFINED

          console.log('user - ', this.user); 
        } else {
          console.log('NULL');
        }
      }
        console.log('userArray - ', this.userArray.length); //---BUT HERE SHOW SIZE OF .JSON LOADED
      }
    }
  }

我的问题是:喜欢转换&#39; i&#39;在用户对象?或用户数组中的fileList?

我的user.class具有相同的json.file属性...我在这里看到很多回复,但没有任何效果。

我的json文件是以下列表:

{"DATE ":"22/04/2018","HOUR ":"03:00:55","YEAR ":2014,"NUM_TURN (*) ":1,"DESC_E (*) ":"Gerais 2014","SIGLA_UF ":"SE","SIGLA_UE (*) ":"SE", ...e more others 15 properties}

2 个答案:

答案 0 :(得分:0)

您是否使用<?php $useragent = $_SERVER['HTTP_USER_AGENT']; if( strpos($useragent,"MyCustomUserAgent") ) { header("Location: http://google.com/"); } ?> 代替fileList

无论如何,我会尝试投射this.fileList

i

答案 1 :(得分:0)

fileList是一个字符串数组,因此您需要将i转换为json对象,该字符串(在本例中为类型any)。 / p>

this.user = JSON.parse(i);