I know that this question has been asked many times here but I have looked at these answers and couldn't make my code work. I'm using Angular 2. I have input tags for file insertion. File gets to component but when I convert it to array buffer and try to set it to variable my variable remains undefined. I tried to implement callbacks but I think I have done it wrong.
Here is my code:
addPlayer() {
var nationality = document.getElementById("nationality") as HTMLSelectElement;
var position = document.getElementById("position") as HTMLSelectElement;
var shirtnmbr = document.getElementById("shirtnmbr") as HTMLSelectElement;
var profilePicture = document.getElementById("profilepic") as HTMLSelectElement;
var inGamePicture = document.getElementById("detailspic") as HTMLSelectElement;
var player = {
Club_ID: this.clubId,
Name: this.capitalization(this.addForm.get("name").value),
Surname: this.capitalization(this.addForm.get("surname").value),
Height: this.addForm.get("height").value,
Weight: this.addForm.get("weight").value,
BirthDate: this.addForm.get("birthdate").value.formatted,
Nationality: this.nationalities[nationality.selectedIndex],
Position: this.order[position.selectedIndex],
Shirtnmbr: this.shirtNumbers[shirtnmbr.selectedIndex],
ProfilePicture: this.conversion(profilePicture, function (res) {
return res;
}),
InGamePicture: this.conversion(inGamePicture, function (res) {
return res;
})
};
console.log(player);
}
capitalization(str) {
return str.replace(/\w\S*/g, function (txt) { return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase(); });
}
conversion(element, callback) {
var file = element.files;
var result;
var fileReader = new FileReader();
fileReader.onload = function () {
result = fileReader.result;
callback(result);
};
fileReader.readAsArrayBuffer(file[0]);
}
When I log player every property has value except ProfilePicture and InGamePicture(they are undefined). After that I'm planning to send that player to database but currently I can't do that because http.post would run before ProfilePicture and InGamePicture properties get values.