gpt4 book ai didi

Angular:从 FileReader 返回 Observable/ES6 Promise

转载 作者:太空狗 更新时间:2023-10-29 17:13:01 24 4
gpt4 key购买 nike

我试图从 FileReader 返回结果,我发现了 this执行。但由于它已经过时,我想知道如何使用 ES6 Promises 或 Rx Observables 实现相同的功能。

下面是我引用上述链接的代码,它按预期工作。

import { Injectable } from '@angular/core';
import * as XLSX from 'xlsx';
import * as XLS from 'xlsx';

@Injectable()
export class ExcelReaderService {

constructor() { }

importFromExcel(ev): JQueryPromise<any> {
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") > 0) {
xlsxflag = true;
}

let fileReader = new FileReader();

fileReader.onload = (ev) => {
let binary = "";
let bytes = new Uint8Array((<any>ev.target).result);
let length = bytes.byteLength;
for (let i = 0; i < 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 = <{}[]>XLS.utils.sheet_to_row_object_array(workbook.Sheets[workbook.SheetNames[0]]);
deferred.resolve(excelInJSON);
}
}

// init read
if (xlsxflag)
fileReader.readAsArrayBuffer((<any>ev.target).files[0]);
else
fileReader.readAsBinaryString((<any>ev.target).files[0]);
} else {
deferred.reject('Invalid file!');
}
return deferred.promise();
}

}

在消费者组件

this.excelReaderService.importFromExcel(ev).then((result) => {
this.detailHeadings = Object.keys(result[0]);
this.detailData = result;
})

如果有人能帮我解决这个问题就太好了,因为我是异步编程的新手。

最佳答案

我就是这样做的,以防万一有人想要一个 Angular 服务来读取 Excel 文件并以内容的 observable 作为 JSON 进行响应。

我正在使用 SheetJS用于读取文件并输出 JSON

import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import * as XLSX from 'xlsx';

@Injectable()
export class ExcelReaderService {

constructor() { }

importFromExcel(ev): Observable<any> {
let workbook;
let excelInJSON;

const fileReader = new FileReader();

// init read
fileReader.readAsArrayBuffer((<any>ev.target).files[0]);

return Observable.create((observer: Subscriber<any[]>): void => {
// if success
fileReader.onload = ((ev: ProgressEvent): void => {
let binary = "";
let bytes = new Uint8Array((<any>ev.target).result);
let length = bytes.byteLength;
for (let i = 0; i < length; i++) {
binary += String.fromCharCode(bytes[i]);
}

// Converts the excel data in to json
workbook = XLSX.read(binary, { type: 'binary', cellDates: true, cellStyles: true });
// only first sheet
excelInJSON = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]);

observer.next(excelInJSON);
observer.complete();
}

// if failed
fileReader.onerror = (error: FileReaderProgressEvent): void => {
observer.error(error);
}
});
}

}

组件,只需将事件传递给该服务,如下所示,它将使用 JSON 进行响应。

this.excelReaderService.importFromExcel(ev)
.subscribe((response: any[]): void => {
// do something with the response
});

关于Angular:从 FileReader 返回 Observable/ES6 Promise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46513123/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com