0

anyone know how i solve it? I added an element to my array with the push function and then tried to access the array at position 3 that was added to the element but not as defined

   readThis(inputValue: any): void {
    this.contImage = inputValue.files.length;
    for (var i = 0; i < inputValue.files.length; i++) {
        let file: File = inputValue.files[i];
        let myReader: FileReader = new FileReader();
        myReader.onloadend = (e) => {
            if(file.size <= 4000000){
                this.imageValues.push(myReader.result);
            }else{
                swal(
                    'Ops! Imagem muito grande',
                    'Algumas imagens não puderam ser enviados pois excede o tamanho maximo de 5 Megas :/',
                    'error'
                );
            }


        }
        myReader.readAsDataURL(file);

    }

    this.editeImage();





}

editeImage(){

    console.log(this.imageValues[3]);



}
  • 3
    You need to call your `editeImage` function after the data is loaded, which means inside the `onloadend` function – Nick Oct 24 '17 at 19:05
  • 1
    Can you do a `console.log(this.imageValues)` and update your question with the output? – JuanDM Oct 24 '17 at 19:06
  • You are calling a position 3 in the array, but you can not guarantee that it is filled. Make an impression of the count of array elements. console.log(this.imageValues.length); – Claudio Castro Oct 24 '17 at 19:07

1 Answers1

0

You're getting tricked by asynchronicity. Where you were previously calling the editeImage function, you had no guarantee that the necessary data was finished loaded. You could call your editeImage function within the onloadend method to ensure you have data to work with.

readThis(inputValue: any): void {
  this.contImage = inputValue.files.length;
  for (var i = 0; i < inputValue.files.length; i++) {
    let file: File = inputValue.files[i];
    let myReader: FileReader = new FileReader();
    myReader.onloadend = (e) => {
      if(file.size <= 4000000){
        this.imageValues.push(myReader.result);
        if(this.imageValues.length === 4) this.editeImage();
      }else{
        swal(
          'Ops! Imagem muito grande',
          'Algumas imagens não puderam ser enviados pois excede o tamanho maximo de 5 Megas :/',
          'error'
        );
      }
    }
    myReader.readAsDataURL(file);

  }

}

editeImage(){ 
    console.log(this.imageValues[3]); 
}
Nick
  • 16,066
  • 3
  • 16
  • 32