【问题标题】:Getting ERROR TypeError: this.fileUpload.upload is not a function出现错误类型错误:this.fileUpload.upload 不是函数
【发布时间】:2020-03-14 15:37:07
【问题描述】:

大家好,我实现了一个以角度上传文件的代码,但问题是当我第一次上传文件时它成功上传,但当我第二次上传时它显示以下错误。

EmployeeDetailComponent.html:39 ERROR TypeError: this.fileUpload.upload is not a function
    at EmployeeDetailComponent.uploadFile (employee-detail.component.ts:92)
    at Object.eval [as handleEvent] (EmployeeDetailComponent.html:39)
    at handleEvent (core.js:34789)
    at callWithDebugContext (core.js:36407)
    at Object.debugHandleEvent [as handleEvent] (core.js:36043)
    at dispatchEvent (core.js:22533)
    at core.js:24430
    at SafeSubscriber.schedulerFn [as _next] (core.js:27889)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:185)
    at SafeSubscriber.next (Subscriber.js:124)

这是我的html代码

<form [formGroup]="profileForm" (ngSubmit)="uploadFile()">
      <div class="form-group">
              <input type="file" name="profile"  (change)="onSelectedFile($event)" />
      </div>
      <div class="form-group">
              <button class="btn btn-success">Upload</button>
      </div>
</form>

一个ts文件就好了。

uploadFile(){
    const formData = new FormData();
    formData.append('profile', this.profileForm.get('profile').value);
    console.log(formData)
    this.fileUpload.upload(formData).subscribe(
      res => {
        this.fileUpload = res;
        console.log(res)
      },
      err => this.error = err,
    );
  }

  onSelectedFile(event) {
    if (event.target.files.length > 0) {
      const file = event.target.files[0];
      this.profileForm.get('profile').setValue(file);
    }
  }

上传文件的服务是。

  upload(formData) {
    return this.http.post<any>(`${this.apiUrl}`, formData, {
      reportProgress: true,
      observe: 'events'
    }).pipe(
      map(event => this.getEventMessage(event, formData)),
      catchError(this.handleError)
    );
  }

【问题讨论】:

  • 订阅后您似乎收到了nullundefined 的回复
  • 下次你使用this.fileUpload.upload(formData)fileUpload将是null

标签: angular angular8


【解决方案1】:

问题出在下面一行:

this.fileUpload = res;

方法被调用后,您将响应存储到服务对象,在这种情况下,它不会有任何upload 方法。

所以,在 Component.TS 中声明一个变量:

response : any;

只需替换这一行:

this.fileUpload = res;

this.response = res;

并在任何地方使用它。

【讨论】:

    猜你喜欢
    • 2018-04-28
    • 2019-02-14
    • 2021-10-02
    • 2021-10-30
    • 2018-11-22
    • 2017-10-12
    • 2020-06-05
    • 2023-03-15
    • 2018-10-21
    相关资源
    最近更新 更多