Angular 7 / Typescript: grab value from within an onload function (upload files, grab content from a file)

Asked

Viewed 408 times

0

I have the code below where I upload a file and want to get its contents in a variable.

For this I use the function onload that gets me the result, which is the contents of the archive.

But the variable gives undefined outside the onload, how to make this result be used outside this function?

if(event.target.files.length > 0) {
    let fileContent;
    let file = event.target.files[0];
    let fileReader = new FileReader();
    fileReader.onload = function() {
        fileContent = fileReader.result;
        console.log(fileContent); //aqui eu tenho o conteúdo completo do arquivo
    };

    fileReader.readAsText(file);

    console.log(fileContent); //aqui é undefined
    }
  }
  • No parameter is passed in fileResult.Have you tried to print the result of the file ? .

  • It will only exist inside the onload because it is the function that is called when it finishes receiving the file

  • @Victorhenrique did not understand which fileResult would be

  • @Eduardovargas yes, I need a way to make that information persist and appear outside that function.

  • You can set the value to a property of your component. But it will only be with the value when function run because it is the same.

  • You think you’ve got some time before the file’s uploaded.

  • @Eduardovargas, right, could show me an example of how to return this result to what I’m looking for?

  • The behavior of the code you shared is what is expected, since it is an asynchronous API. What do you want to do with the result later? It’ll be easier to help you if we understand the context.

  • @Leonardolima I want to save this value in a variable and then mount an object and save via api.

Show 4 more comments

1 answer

0


The problem I was having was that the content of the onload function happened after the rest of the code, leaving this data as null.

Solution, redo the function

async uploadFile(event) {

    var reader = new FileReader();
    let file = event.target.files[0];

    reader.onload = ((file: any) => {
      return (e: Event) => {
        this.document.description = e.srcElement.result; 
        //tenho um objeto document, e adiciono o conteúdo do arquivo encontrado pelo onload


        this.myFunction(this.document);
        //pulo do gato: chamar a continuidade do script dentro do onload, pois o conteúdo do result só existe dentro dessa função, por isso, passe esse conteúdo para o objeto e o envie como parâmetro, assim esse dado irá ser enviado a próxima função e vc poderá o manipular.

      }
    })(file);

    reader.readAsText(file);
  }

  async myFunction(document) {
    console.log(document.description);
    //a descrição pega pelo onload continua existindo c:
    //o resto do seu código
  }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.