angularfile-uploadasyncfileupload

The value assigned to a local variable got undefined in angular 4


I am doing a file upload and in on change event I am reading the file using FileReader and assigning the string to a variable. But in submit method, the variable is shown undefined.

My code

Html:

 <form #yourForm="ngForm" (ngSubmit)="addDocument()">
<div class="col-md-12">
      <div class="form-group form-black">
        <label class="control-label">Select file: </label>
        <input type="text" [(ngModel)]="Name" name="Name" class="form-group" />
        <input type="file" #fileupload [(ngModel)]="myFile"  name="myFile" (change)="fileChange(fileupload.files)" />

      </div>
    </div>
    <div class="col-md-12">
      <div class="form-group form-black pull-right">
        <button type="submit">Submit</button>
      </div>
    </div>
  </form>

component.ts

document: IDocuments = {docstream:''};
 Name: string;
  myFile: File; /* property of File type */
  upFile: File;
  fileStream: string;
  fileChange(files: any) {

   this.upFile = files[0];
    this.Name = this.upFile.name;
   this.getBase64(this.upFile, function (e) {
  let result = e.target.result;
  this.fileStream=result.split(',')[1];      
  console.log("In: "+this.fileStream);

})
console.log("Out: "+this.fileStream);
this.document.docstream = this.fileStream;
  } 
  getBase64(file, onLoadCallback): string {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = onLoadCallback;
return reader.result;
 }

 addDocument(): void {    
console.log("addDocument: "+this.fileStream);
console.log(this.document.docstream);

this._fileuploaderService.uploadDocument(this.document)
  .subscribe(s => { });
 }


console.log("In: "+this.fileStream); //is showing the result 

but

console.log("Out: "+this.fileStream); //is showing undefined 

console.log("addDocument: "+this.fileStream); //is showing undefined 

What will be the issue? After the change event, this.fileStream should show some result, shouldn't it?


Solution

  • Change

    this.getBase64(this.upFile, function (e) {
    

    to

    this.getBase64(this.upFile, (e) => {
    

    to prevent this pointing to the caller instead to the class where the function is defined.

    For more information see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions