如何在 angular 7 中同步读取 csv 文件

How to read a csv file sychonously in angular 7

我正在尝试同步读取位于网络上的 csv 文件。给定以下代码

export class AppComponent implements OnInit {
  name = 'Angular';
  apiUrl = 'https://www.techiediaries.com/api/data.json';
  csvFileURL = 'https://www.cdc.gov/coronavirus/2019-ncov/map-data-cases.csv';

  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    console.log('start');
    const result = this.fetchData();
    console.log(result);
    console.log('end');
  }

  private async fetchData() {
    let dataset: any;
    const promise = this.httpClient
      .get(this.csvFileURL, { responseType: 'text' })
      .toPromise();
    // console.log(promise);
    await promise
      .then((data) => {
        //console.log('Promise resolved with: ' + JSON.stringify(data));
        dataset = data;
        console.log('inside then statement');

        return data;
      })
      .catch((error) => {
        console.log('Promise rejected with ' + JSON.stringify(error));
      });
    return dataset;
  }
}

我希望在控制台中看到的是: 开始 数据的价值 在 then 语句里面 结束

我还想要 return 数据的 fetchdata 函数

我还尝试了以下变体:

  1. http.get(...).订阅
  2. http.get(...).toPromise

两者都是异步执行的。我目前的版本使用async和await这个问题的完整代码是here它也是异步执行的

由于其他项目限制,我只能使用 Angular 7。

相信我,您不想同步执行它,因为 javascript 是单线程的,同步执行会阻止您的用户,直到您通过单击按钮或执行任何操作来获取和解析 csv其他在您的网络应用程序上。

代码或您解释的内容可以像下面这样实现:-

export class AppComponent implements OnInit {
  name = 'Angular';
  apiUrl = 'https://www.techiediaries.com/api/data.json';
  csvFileURL = 'https://www.cdc.gov/coronavirus/2019-ncov/map-data-cases.csv';

  constructor(private httpClient: HttpClient) {}

  ngOnInit() {
    this.fetchData.subscribe((csvData) => {
         //what ever part of data you want to use its inside csvData. Remember its text at this moment, with comma separated strings, not a json. as you have sent responseType as text below. If you want a json alread parsed for you remove the second parameter from get call.
    })
  }

  private fetchData() {
    return this.httpClient
      .get(this.csvFileURL, { responseType: 'text' });
}