订阅中定义的变量恢复为未定义

问题描述

我是一个初学者,所以我认为我可能做错了什么。 我尝试编写一个CRUD,以便在创建团队时向团队添加图像。 我将文件名存储在数据库中,然后将图像上传到服务器后端。几天前,一切工作正常,但从昨天开始,它将不会上传文件。这是因为在每次对输入进行更改时都定义的变量this.currentFile在从API接收到的数据分配给this.team后也返回到undefined(这也是未定义的,而{{1} })。

我发现有人说datathis中没有定义,但我的定义很好。 我真的不知道出什么问题了,已经花了几个小时了,我没有找到任何可以帮助的东西,所以任何帮助将不胜感激!

这是subscribe()中的submit()方法

team-form.component.ts

这是submit() { this.bindToModel(); if(this.team.id == undefined) { //this.team and this.currentFile are well defined this.teamService.save(this.team).subscribe( (data) => { this.team = data; //this.team and this.currentFile get back to undefined at this point,even after data was assigned to this.team if(this.currentFile != undefined) { this.uploadService.upload(this.currentFile,this.team.id).subscribe({ error: err => showError(this.toasterService,err.error.message),complete: () => { this.currentFile = null; } }); } },error => showError(this.toasterService,error.message),() => { this.closeModalAndMessageSuccess()} ); }else { this.teamService.update(this.team).subscribe({ error: err => showError(this.toasterService,complete: () => this.closeModalAndMessageSuccess() }) } } 方法

bindToModel()

用户选择文件时触发bindToModel() { this.team.contestTypes = this.selectedContestTypes; this.selectedContestTypes = []; this.team.label = this.teamForm.get('label').value; if(this.currentFile != undefined) { this.team.logoPath = this.currentFile.name; } else { this.team.logoPath = null; } } 方法

selectFile(event)

以及输入的html:

selectFile(event) {
    let reader = new FileReader();
    if(event.target.files && event.target.files.length > 0) {
      this.currentFile = event.target.files[0];
    }
  }

编辑:

因此,按照@ aditya_adi_98的建议,我打电话来上传文件并同时保存小组。 现在,我认为后端控制器方法语法存在问题,因为出现以下错误:

<div class="labelAndUpload">
    <label for="teamLogo"> Logo de l'équipe</label>
    <input type="file"
       id="teamLogo"
       (change)="selectFile($event)">  
</div>

这是我的新Content type 'multipart/form-data;boundary=---------------------------29202803211777703984242234963' not supported 方法

submit()

现在请求

  submit() {
    this.bindToModel();
    if(this.team.id == undefined) {
      var stringTeam = JSON.stringify(this.team);
      const frmData = new FormData();
      frmData.append("team",stringTeam);
      frmData.append("file",this.currentFile);

      this.teamService.save(frmData).subscribe({
        error: err => showError(this.toasterService,complete: () => this.closeModalAndMessageSuccess()
      });
    } else {
      this.teamService.update(this.team).subscribe({
        error: err => showError(this.toasterService,complete: () => this.closeModalAndMessageSuccess()
      })
    }
  }

和后端控制器方法(java)。尚未修改它以考虑到我正在传递的文件,但我只是希望该方法此刻能够正确接收请求。

public save(formData: FormData) {
  return this.http.post<Team>(this.teamsUrl,formData);
}

任何了解Java的人都可以帮助我吗?

解决方法

您为什么要进行两个http调用,而一次调用中却可以这样做。例如使用this.teamService.save(this.team)

发送文件/图像
  const frmData = new FormData();      
  frmData.append("Upload",this.currentFile);
  frmData.append("team",this.team)      
      

编辑

您还可以执行此操作以观看文件上传,最好发送完整的请求,然后等待响应

this.http.post(BACKEND_URL+'/testfileupload',frmData,{responseType : 'text',reportProgress:true,observe :'events'})
    .subscribe(      
      (event: HttpEvent<any>)=>{
        switch(event.type){
          case HttpEventType.Sent:
            
            break;

          case HttpEventType.ResponseHeader:
            
            break;

          case HttpEventType.UploadProgress:
            this.progress = Math.round(event.loaded / event.total * 100);
            this.showupload=true;
            this.changedetector.detectChanges()
            console.log(`uploaded ${this.progress}`);
            break;

          case HttpEventType.Response:
            this.showupload=false;
            this.doneupload=true;
            this.progress=0;
            this.currentFile=''
            this.changedetector.detectChanges(); 
            console.log("uploaded successfully")

            this.teamaddedsuccessful()
            setTimeout(()=>{
              this.doneupload=false;
              this.changedetector.detectChanges();
              this.modalService.dismissAll();
              this.toastr.success("File Uploaded Successful","Success")
              this.filetitle='';},3000)
        }
    
      },res=>{
        if(res.status == 404)
        {
          this.showupload=false;
          this.progress=0;
          this.changedetector.detectChanges(); 
          this.toastr.error("Error in File Upload","Error")
        }
      })

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...