'How to read a csv file sychonously in angular 7 [duplicate]
I am trying to read a file csv located on the web synchronously. Given the following code
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;
}
}
What I would like to see in the console is: start data's value inside then statement end
I would also like the fetchdata function to return data
I have also tried the following variants:
- http.get(...).subscribe
- http.get(...).toPromise
Both execute asynchronously. My current version using async and await The complete code for this problem is here It also executes asynchronously.
I am restricted to Angular 7, by other project constraints.
Solution 1:[1]
Believe me you don't want to do it synchronously, as javascript is single threaded and doing it synchronously will block your user, until you fetch and parse the csv from even clicking a button or doing anything else on your web app.
Code or what you explained can be achieved like below :-
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' });
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Aakash Garg |