[英]Javascript - get value from FileReader asynchronous onload method
我知道這個問題在這里已經問過很多遍了,但是我已經看過這些答案了,無法使我的代碼正常工作。 我正在使用Angular2。我有用於插入文件的輸入標簽。 文件進入組件,但是當我將其轉換為數組緩沖區並嘗試將其設置為變量時,我的變量仍未定義。 我嘗試實現回調,但是我認為做錯了。
這是我的代碼:
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()
的返回值的值,因為它們從不返回任何內容,因此它們始終是undefined
。 您提供了一個您要調用的回調,但是它實際上不執行任何操作(返回從未處理過的參數)。
在繼續操作之前,您需要同步完成兩個FileReader
操作。 如果您只能異步獲取結果,那么這聽起來像Promises的工作,這是當今使用多個異步操作處理控制流的首選方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.