【发布时间】:2023-12-17 16:30:01
【问题描述】:
我知道这个问题在这里被问过很多次,但我查看了这些答案,但无法让我的代码正常工作。我正在使用 Angular 2。 我有用于文件插入的输入标签。文件进入组件,但是当我将其转换为数组缓冲区并尝试将其设置为变量时,我的变量仍未定义。我试图实现回调,但我认为我做错了。
这是我的代码:
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]);
}
当我记录播放器时,除了 ProfilePicture 和 InGamePicture(它们是未定义的)之外,每个属性都有值。之后我打算将该玩家发送到数据库,但目前我不能这样做,因为 http.post 会在 ProfilePicture 和 InGamePicture 属性获取值之前运行。
【问题讨论】:
-
您需要确保两个回调都已完成,然后再将数据发送到我假设的 HTTP?也只是一个建议,你应该使用 Promise 或者因为使用 Angular 2 那么你应该使用 RXJS 而不是回调。
-
@LiverpoolOwen 你能举个例子吗?
标签: javascript angular filereader