分配给局部变量的值在角度4中得到了未定义

问题描述:

我正在执行文件上载并处于更改事件中我正在使用FileReader读取文件并将字符串分配给变量。但在提交方法中,变量显示为未定义。分配给局部变量的值在角度4中得到了未定义

我的代码

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指向呼叫者而不是其中函数定义的类。

欲了解更多信息,请参阅https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

+1

非常感谢你...你节省了我的时间:) –