title: Angular: Return Observable / ES6 Promise from FileReader
body: <p>I was trying to return result from <code>FileReader</code> and I found <a href="https://gist.github.com/jollytoad/4201905" rel="noreferrer">this</a> implementation. But since it is outdated, I'm wondering how to implement the same using ES6 <code>Promises</code> or Rx <code>Observables</code>. </p>
  
  <p>Below is my code with reference to the aforementioned link and it works as expected.</p>
  
  <pre><code>import { Injectable } from '@angular/core';
  import * as XLSX from 'xlsx';
  import * as XLS from 'xlsx';
  
  @Injectable()
  export class ExcelReaderService {
  
    constructor() { }
  
    importFromExcel(ev): JQueryPromise&lt;any&gt; {
      let deferred = $.Deferred();
  
      let regex = /^([a-zA-Z0-9\s_\\.\-:])+(.xlsx|.xls)$/;
  
      let workbook;
      let excelInJSON;
  
      if (regex.test(ev.target.files[0].name.toString().toLowerCase())) {
        let xlsxflag = false; /*Flag for checking whether excel is .xls format or .xlsx format*/
        if (ev.target.files[0].name.toString().toLowerCase().indexOf(".xlsx") &gt; 0) {
          xlsxflag = true;
        }
  
        let fileReader = new FileReader();
  
        fileReader.onload = (ev) =&gt; {
          let binary = "";
          let bytes = new Uint8Array((&lt;any&gt;ev.target).result);
          let length = bytes.byteLength;
          for (let i = 0; i &lt; length; i++) {
            binary += String.fromCharCode(bytes[i]);
          }
  
          /*Converts the excel data in to json*/
          if (xlsxflag) {
            workbook = XLSX.read(binary, { type: 'binary', cellDates: true, cellStyles: true });
            // only first sheet
            excelInJSON = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);
            deferred.resolve(excelInJSON);
          }
          else {
            workbook = XLS.read(binary, { type: 'binary', cellDates: true, cellStyles: true });
            excelInJSON = &lt;{}[]&gt;XLS.utils.sheet_to_row_object_array(workbook.Sheets[workbook.SheetNames[0]]);
            deferred.resolve(excelInJSON);
          }
        }
  
        // init read
        if (xlsxflag)
          fileReader.readAsArrayBuffer((&lt;any&gt;ev.target).files[0]);
        else
          fileReader.readAsBinaryString((&lt;any&gt;ev.target).files[0]);
      } else {
        deferred.reject('Invalid file!');
      }
      return deferred.promise();
    }
  
  }
  </code></pre>
  
  <p>In the consumer <code>component</code></p>
  
  <pre><code>this.excelReaderService.importFromExcel(ev).then((result) =&gt; {
      this.detailHeadings = Object.keys(result[0]);
      this.detailData = result;
  })
  </code></pre>
  
  <p>It'll be great if someone helps me with this as I'm new to asynchronous programming.</p>