【问题标题】:Type 'Observable<void>' is not assignable to type 'Observable<HttpEvent<any>>' Type 'void' is not assignable to type 'HttpEvent<any>'类型“Observable<void>”不可分配给类型“Observable<HttpEvent<any>>”类型“void”不可分配给类型“HttpEvent<any>”
【发布时间】:2021-09-23 04:46:29
【问题描述】:

我正在尝试为上传添加进度条并收到此错误。 而且 event.type 也是未定义的。

请帮我找到解决办法。谢谢

我附上了我已经完成的代码。

HttpRequest 代码

uploadfile(file: any): Observable<HttpEvent<any>>{
  return this.InfoService.getId().pipe(
      concatMap((result) => {
          return this.schemaService.getSchema().pipe(schema => {
              const url = '/url';
              return this.http.post(url, file, {headers: this.headers, reportProgress: true});
      }).toPromise().then((resolved) => {
          this.successMessage('Upload Success',MessageIcon, " uploaded successfully");
      })
  }));
}

订阅方式:


uploadfile(){
  const formData = new FormData();
  formData.append('file', this.uploadForm.get('item').value);
  this.uploadService.uploadfile(formData).subscribe((event : HttpEvent<any>) => {
    console.log(event)
    switch (event.type) {
      case HttpEventType.UploadProgress:
        this.progress = Math.round(event.loaded / event.total * 100);
        console.log(`Uploaded! ${this.progress}%`);
        break;
      case HttpEventType.Response:
        console.log('successfull!', event.body);
        setTimeout(() => {
          this.progress = 0;
        }, 1500);

    }
  })  
}

【问题讨论】:

    标签: angular xmlhttprequest


    【解决方案1】:
    1. 我不确定您要对 pipe 函数的 schema 参数做什么。 pipe 将 RxJS 运算符作为参数。从用法来看,我假设你想在这里使用像 concatMap 这样的映射运算符。

    2. 函数的返回类型声明为Observable&lt;HttpEvent&lt;any&gt;&gt;。但是您正在使用 toPromise() 函数将 Observable 转换为 Promise。您可以改用tap 运算符。

    试试下面的

    uploadfile(file: any): Observable<HttpEvent<any>> {
      return this.InfoService.getId().pipe(
        concatMap((result) => this.schemaService.getSchema()),
        concatMap((schema) => {
          const url = '/url';
          return this.http.post(url, file, {
            headers: this.headers,
            reportProgress: true,
            observe: "events"              // <-- also try adding `observe`
          });
        }),
        tap(() => this.successMessage('Upload Success', MessageIcon, " uploaded successfully"))
      );
    }
    

    【讨论】:

    • 非常感谢它有效。 toPromise() 是问题所在。
    • @tiana:还要注意 toPromise() 将在 RxJS 8 中消失:indepth.dev/posts/1287/…
    • 非常感谢您的便条。
    猜你喜欢
    • 2018-04-19
    • 1970-01-01
    • 2023-04-10
    • 2021-02-06
    • 1970-01-01
    • 2019-01-12
    • 2020-08-24
    • 2021-05-21
    • 1970-01-01
    相关资源
    最近更新 更多