cyberbeast
cyberbeast

Reputation: 698

Accessing filereader content outside onload method in Angular5/6?

I am trying to read a file for which I have the following code snippet.

readFile(file: File) {
    var reader = new FileReader();
    console.log(reader.readyState);
    reader.onload = () => {
        console.log(reader.result);
    };
    reader.readAsText(file);
}

As expected the console.log() prints the content of the file at the reader's onload event. However, I am trying to extract this output as a return value from my readFile method.

For example,

onSubmit() {
    let output = this.readFile(this.newImportForm.value.dataFile);
    console.log(output);
}

How can I return the file contents back as a string? I could put together a solution that involves emitting events and doing something complicated, but I want to explore a more elegant solution.

Thanks, in advance :)

Upvotes: 3

Views: 2501

Answers (1)

Andreas
Andreas

Reputation: 346

You cannot return the string directly since FileReader reads the content asynchronously.

A more elegant solution would be to return a Promise or Observable from readFile. For example

readFile(file: File): Observable<string> {
   const sub = new Subject<string>();
   var reader = new FileReader();

   reader.onload = () => {
      const content: string = reader.result as string;
      sub.next(content);
      sub.complete();
   };

   reader.readAsText(file);
   return sub.asObservable();
}

This way you can subscribe to the returned Observable like this

fileSelected(ev) {
    const file = ev.target.files[0];
    this.readFile(file).subscribe((output) => {
      console.log(output);
    })
  }

Upvotes: 9

Related Questions