typescriptangular10

Array element is null when I try to get with index


I have a function that get an image size:

  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;
  }

I use it in another service:

  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;
  }

The 3 console log returns first the array, but the length is 0 and when I want to get an element it is undefined:

enter image description here


Solution

  • Actually getImageSize is async function. You should promisify it first. Like this

      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);
        });
      }
    

    And then use it in another service with await

    let iconSize = await this.utilService.getImageSize(this.icon[0]) ;