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.