I am new to Angular and I'm working on implementing a feature for uploading and registering content using CSV files.
Here is the code snippet:
parts.component.html
<div class="well">
<form>
<div class="row">
<div class="col-md-10">
<input class="form-control" id="file" name="file" (change)="readCsvData($event)" type="file" accept="text/plain">
</div>
<div class="col-md-2">
<button class="btn btn-success" type="submit">Submit file</button>
</div>
</div>
</form>
</div>
parts.component.ts
readCsvData(){
let csvUrl = event.target;
this.partService.upload(csvUrl)
}
part.service.ts
public upload(input: any){
let url = this.partsUrl;
let body = this.extractData(input);
console.log(body);
// return this.http.post()
}
public extractData(data: any) {
const file = data.files[0];
const reader = new FileReader();
reader.onload = function(e) {
const content = reader.result;
var lines = content.split("\n");
var result = [];
var headers = lines[0].split(",");
for(var i = 1; i < lines.length; i++){
var obj = {};
var currentline = lines[i].split(",");
for(var j = 0; j < headers.length; j++){
obj[headers[j]] = currentline[j];
}
result.push(obj);
}
JSON.stringify(result);
}
reader.readAsText(file);
}
However, the Upload function is only returning 'Undefined' in the variable 'body', when it should actually return the array of objects from the extractData function.
Any assistance or advice would be greatly appreciated!