分配给局部变量的值在 angular 4 中未定义

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

我正在上传文件,在发生更改事件时,我正在使用 FileReader 读取文件并将字符串分配给变量。但是在提交方法中,变量显示未定义。

我的代码

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 

但是

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

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

会出现什么问题?在更改事件之后,this.fileStream 应该会显示一些结果,不是吗?

改变

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

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

以防止 this 指向调用者而不是 class 定义函数的地方。

有关详细信息,请参阅 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions