angular - TypeScript (Angular) - 逐行读取文本文件
问题描述
我在逐行阅读文本文件时遇到问题。使用 console.log(file) 效果很好,但我需要每个特定的行对它们做一些事情,所以这就是我到目前为止所做的。
在 api.service.ts 我有一个从服务器下载文件的函数,函数本身如下所示:
getFile(url: string): Observable<File> {
return this.httpClient.get<File>(url, {responseType: "text"});
}
然后在 app.component.ts 我定义了私有的“resultFile:File”字段并将传入的文件分配给这个变量
getFile() {
this.apiService.getFile('http://127.0.0.1:8000/media/results/MINERvA/CC0pi/v1.0/nuwro.txt').subscribe(file => {
this.resultFile = file;
console.log(this.resultFile);
});
}
正如我在使用 console.log() 打印 resultFile 的内容之前提到的那样工作得很好。文件格式正确(带有新行),但是当我遍历 resultFile
for (const line of resultFile){
console.log(line);
}
它打印每个字符而不是每一行。我认为问题可能是 responseType: "text" 将内容转换为纯字符串,但我找不到任何解决方案。抱歉这个愚蠢的问题,但我以前从未使用过 JS/TS。
解决方案
Try splitting the lines with newLines:
for (const line of resultFile.split(/[\r\n]+/)){
console.log(line);
}
Refer this to see line seperators: Do line endings differ between Windows and Linux?
推荐阅读
- jenkins - Jenkins 可以仅通过配置和作业进行备份吗?
- java - 无法使用 Apache POI 写入 Excel
- amazon-web-services - 配置后nginx连接被拒绝
- matlab - Matlab - 多边形和线的交点
- angular - still confused Routing and child Nativescript angular
- vba - 循环通过用户窗体
- javascript - Mapbox悬停弹出窗口不起作用
- ios - UITable 视图中的单元格队列大小
- linux-kernel - Linux 发行版如何影响内核行为
- php - mPDF - 仅显示一次表格页脚 (tfoot)