In our database, we store words along with their categories. I have a new requirement to enable the word administrator to upload multiple words at once using a CSV file. Currently, our system only allows for single-word additions at a time. My solution was to call the existing function repeatedly for each word in the CSV file.
Below is the constructor and dependencies of my component:
export class AdminComponent implements OnInit {
currentJustify = 'start';
processing = false;
error = false;
errorAdd = false;
word: IWord;
showTable = false;
@Input() wordArea: string;
@Input() idArea: number;
addWordMessage: string;
categoryItems: string[] = ['Category...', 'awl','stem', 'hi', 'med', 'low'];
category: string = this.categoryItems[0];
sessionHistory: string[] = [];
index = 1;
constructor(private _admin: AdminService, public router: Router) { }
Here's the iterative function that I'll be utilizing:
addWord(wordArea:string, category:string): void {
this.processing = true;
this.error = false;
this.errorAdd = false;
this._admin.postWord(wordArea, category)
.subscribe
(res => {
this.processing = false;
this.sessionHistory[this.index] = wordArea + ' is added to ' + category + ' category.'
this.index++;
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log('Client-side Error occured');
} else {
this.errorAdd = true;
this.processing = false;
console.log('Server-side Error occured');
}
}
);
}
Here are the functions I've developed up to now:
fileUploadListener($event:any):void{
this.csvadd($event.target, this.addWord);
console.log('out of it');
}
csvadd(csv: any, callback): void { console.log('here')
var file:File = csv.files[0];
var self = this;
var reader:FileReader = new FileReader();
var wordArea:string;
var category:string;
var array;
var fields;
this.processing = true;
this.error = false;
this.errorAdd = false;
console.log('getting ready to read CSV file')
reader.readAsText(file);
reader.onloadend = function (e) {
var csvData = reader.result;
console.log(csvData);
fields = csvData.split('\n');
for (let i in fields) {
console.log('in loop');
var array = fields[i].split(',');
console.log(array);
wordArea=array[0];
console.log(wordArea);
category=array[1];
console.log(category);
callback(wordArea, category);
console.log('finished adding word')}
};
reader.onerror = function () {
console.log('Unable to read ' + file);
};
}
Based on my understanding of TypeScript and JavaScript, using a callback function is necessary in this scenario to capture data from the file reader. However, despite implementing this approach, the functionality did not work as expected.
Do you think I'm approaching this task correctly? Should I consider an alternative method, or is there a crucial element that I may have overlooked?
Thank you!