我在逐行读取文本文件时遇到问题。使用console.log(file)可以很好地工作,但是我需要每一行都可以对它们进行处理,所以这是我到目前为止所做的。
在api.service.ts中,我有一个从服务器下载文件的函数,该函数本身看起来像这样:
getFile(url: string): Observable<File> {
return this.httpClient.get<File>(url, {responseType: "text"});
}
然后在app.component.ts中,定义私有(private)的'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。
最佳答案
尝试使用newLines分割行:
for (const line of resultFile.split(/[\r\n]+/)){
console.log(line);
}
引用此以查看行分隔符:ojita