作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我知道这个问题已经被问过很多次了,但我已经查看了这些答案,但无法使我的代码工作。我正在使用 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 属性获取值之前运行。
最佳答案
您将 ProfilePicture
和 InGamePicture
设置为等于 conversion()
的返回值的值,该值永远不会返回任何内容,因此它们始终会未定义。您提供了一个调用的回调,但它实际上什么也没做(返回从未处理过的参数)。
您需要同步完成两个 FileReader
操作才能继续。如果您只能异步获取结果,那么这听起来像是 Promises 的工作,目前处理多个异步操作控制流的首选方法。
关于Javascript - 从 FileReader 异步 onload 方法获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46075032/
我是一名优秀的程序员,十分优秀!