Skip to content Skip to sidebar Skip to footer

Stuggling To Use Function With Async Onload Method With In A Service In Angular - Same Function Works Perfect In Component?

I have build a component in Angular that imports an excel file and convert it into an array and then displays the content on the excel file on the page as a table. This works perfe

Solution 1:

The idea to use an Observable to handle the async functions look fine. The only issue is, at the moment, no observable is created. You could create one using new Observable construct.

Try the following

import { Observable } from 'rxjs';

importFile(event: any): Observable<any> {
  return new Observable(subscriber => {
    const fileToUpload: DataTransfer = <DataTransfer>event.target;
    if (fileToUpload.files.length !== 1)
      subscriber.error('Can not upload multiple files');  // <-- emit error

    const fileReader: FileReader = new FileReader();

    fileReader.onload = (event: any) => {
      const binstring: string = event.target.result;
      const workbook: excelhandler.WorkBook = excelhandler.read(binstring, {
        type: 'binary',
      });
      const worksheetName: string = workbook.SheetNames[0];
      const worksheet: excelhandler.WorkSheet = workbook.Sheets[worksheetName];
      const importedExcelData = excelhandler.utils.sheet_to_json(worksheet, {
        header: 1,
      });
      subscriber.next(importedExcelData);  // <-- emit notification
      subscriber.complete();  // <-- complete and close the subscription
    };

    fileReader.readAsBinaryString(fileToUpload.files[0]);
  });
}

Since we are sending error notifications, you could pass an error callback in the subscription to capture them.

importFile(event: any) {
  this.dataService.importFile(event).subscribe({
    next: (importedExcelData: any) => this.importedExcelData = importedExcelData,
    error: (error: any) => console.log(error)
  });
}

More info about Observables could be found here


Post a Comment for "Stuggling To Use Function With Async Onload Method With In A Service In Angular - Same Function Works Perfect In Component?"