当我尝试获取索引时,数组元素为空
Array element is null when i try to get with index
我有一个获取图像大小的函数:
getImageSize(fileUploaded: File): Number[]{
let size : Number[] = [];
let _URL = window.URL || window.webkitURL;
let file, img;
file = fileUploaded;
img = new Image();
img.onload = function() {
size.push(Number(this.width));
size.push(Number(this.height));
};
img.onerror = function() {
//alert( "not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
return size;
}
我在另一个服务中使用它:
let iconSize = this.utilService.getImageSize(this.icon[0]) ;
console.log(iconSize);
console.log(iconSize.length);
console.log(iconSize[0]);
if(Number(iconSize[0]) !== 512 || Number(iconSize[1]) !== 512) {
this.notifications.create(
'Error',
'Icon resolution must be 512*512',
NotificationType.Error,
{ theClass: 'outline primary', timeOut: 6000, showProgressBar: false }
);
return;
}
3控制台日志returns首先是数组,但长度为0,当我想获取一个元素时,它是未定义的:
实际上getImageSize
是异步函数。你应该先 promisify
它。像这样
getImageSize(fileUploaded: File) {
return new Promise((resolve, reject) => {
const size: number[] = [];
const _URL = window.URL || window.webkitURL;
let file, img;
file = fileUploaded;
img = new Image();
img.onload = function() {
size.push(Number(this.width));
size.push(Number(this.height));
resolve(size);
};
img.onerror = function() {
reject('not a valid file: ' + file.type);
};
img.src = _URL.createObjectURL(file);
});
}
然后在另一个服务中使用 await
let iconSize = await this.utilService.getImageSize(this.icon[0]) ;
我有一个获取图像大小的函数:
getImageSize(fileUploaded: File): Number[]{
let size : Number[] = [];
let _URL = window.URL || window.webkitURL;
let file, img;
file = fileUploaded;
img = new Image();
img.onload = function() {
size.push(Number(this.width));
size.push(Number(this.height));
};
img.onerror = function() {
//alert( "not a valid file: " + file.type);
};
img.src = _URL.createObjectURL(file);
return size;
}
我在另一个服务中使用它:
let iconSize = this.utilService.getImageSize(this.icon[0]) ;
console.log(iconSize);
console.log(iconSize.length);
console.log(iconSize[0]);
if(Number(iconSize[0]) !== 512 || Number(iconSize[1]) !== 512) {
this.notifications.create(
'Error',
'Icon resolution must be 512*512',
NotificationType.Error,
{ theClass: 'outline primary', timeOut: 6000, showProgressBar: false }
);
return;
}
3控制台日志returns首先是数组,但长度为0,当我想获取一个元素时,它是未定义的:
实际上getImageSize
是异步函数。你应该先 promisify
它。像这样
getImageSize(fileUploaded: File) {
return new Promise((resolve, reject) => {
const size: number[] = [];
const _URL = window.URL || window.webkitURL;
let file, img;
file = fileUploaded;
img = new Image();
img.onload = function() {
size.push(Number(this.width));
size.push(Number(this.height));
resolve(size);
};
img.onerror = function() {
reject('not a valid file: ' + file.type);
};
img.src = _URL.createObjectURL(file);
});
}
然后在另一个服务中使用 await
let iconSize = await this.utilService.getImageSize(this.icon[0]) ;