0

I have this code in Angular

import { Component } from '@angular/core';
import {NgForm} from "@angular/forms";

@Component({
  selector: 'app-add-route',
  templateUrl: './add-route.component.html',
  styleUrls: ['./add-route.component.scss']
})
export class AddRouteComponent {
  public fileContent: string;

    constructor() { }

    onSubmit(form: NgForm) {
    }

    getFile(event) {
      let file = event.target.files[0];
      let filename = file.name;
      let result;

      if((filename.split('.').pop()) === 'gpx') {
        let reader = new FileReader();
        reader.readAsText(file);
        this.fileContent = // what should be here?
      }
   }  

}

I would like to access the file from input file from the form (which must be type of .gpx), get the content (using FileReader()). How can I store filecontent once upon its loaded into class variable fileContent?

Angelux
  • 89
  • 1
  • 11
  • https://stackoverflow.com/questions/13729301/html5-file-api-how-to-see-the-result-of-readastext – R. Richards Feb 24 '18 at 20:33
  • Well, this doesnt work. When I add reader.onload = function (e) { result = e.target.result; } this.fileContent = result; and print it to console its undefined. Yea, the result its stored in the e.target.result but my question is- how can I store it in the class variable. – Angelux Feb 24 '18 at 20:38
  • My *guess*: `reader.onload = (e: any) => { this.fileContent = e.target.result; };` – R. Richards Feb 24 '18 at 20:56
  • No, that does not working. Its still undefined. – Angelux Feb 24 '18 at 21:19
  • Can you add, or show the code you are using to check `this.fileContent`? You would need to do that in the same `{ }` block where the variable gets set. So, something like this: `reader.onload = (e: any) => { this.fileContent = e.target.result; console.log(this.fileContent); };` Checking outside of that would always return undefined. – R. Richards Feb 24 '18 at 21:24
  • Yea I was calling that outside of a function. Now its working fine. – Angelux Feb 24 '18 at 22:09

1 Answers1

0

To get the results of readAsText function in Typescript, you need to set up an arrow function for the onload event that the FileReader fires.

getFile(event) {
  const file = event.target.files[0];
  const filename = file.name;

  if ((filename.split('.').pop()) === 'gpx') {
    const reader = new FileReader();
    reader.readAsText(file);
    reader.onload = (e: any) => {
        this.fileContent = e.target.result;
        console.log(this.fileContent);
    };
  }
}

Then, from within the body of the arrow function, you can access the file contents via the e.target.result (e being the event). From there, you can do what you like the data.

R. Richards
  • 24,603
  • 10
  • 64
  • 64