We have a database of words and categories. My requirement is to allow word admin to add many words at once through a csv file. Currently we have a system that can add a word at once. So my idea was to just call that function as many times as words in the csv file.
Here is my component file constructor and injections
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) { }
Now this is the function I'll be calling iteratively.
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');
}
}
);
}
And these are the functions I've created so far:
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('here 2')
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('final')}
};
reader.onerror = function () {
console.log('Unable to read ' + file);
};
}
From what I've understood from figuring out how to use Typescript and Javascript, you have to use a callback function for this because otherwise you can't get the information from the file reader. So I did that, but that did not work.
Am I going about this whole thing correctly? Should I take another approach, or is there something here I'm missing?
Thank you!