分配给局部变量的值在角度4

时间:2017-10-12 06:19:38

标签: angular file-upload asyncfileupload

我正在进行文件上传,在更改事件中,我正在使用FileReader读取文件并将字符串分配给变量。但是在submit方法中,变量显示为undefined。

我的代码

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 

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

1 个答案:

答案 0 :(得分:1)

更改

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