typescript 在angular中使用http请求时,我们可以订阅多个东西吗?

d5vmydt9  于 2023-02-25  发布在  TypeScript
关注(0)|答案(1)|浏览(123)

在Angular http客户端的帮助下发送表单数据,现在我不仅想订阅事件,还想订阅从服务器返回的数据。事件用于显示进度条,数据是我想向用户显示的内容。这是代码片段:

const req = new HttpRequest('POST', url, newFormData, {
    reportProgress: true,
    responseType: 'text' as 'json'
  });

  // create a new progress-subject for every file
  const progress = new Subject<number>();

  // send the http-request and subscribe for progress-updates

  this.http.request(req).subscribe(event => {
    if (event.type === HttpEventType.UploadProgress) {
      // calculate the progress percentage
      const percentDone = Math.round(100 * event.loaded / event.total);

      // pass the percentage into the progress-stream
      progress.next(percentDone);
    } else if (event instanceof HttpResponse) {
      // Close the progress-stream if we get an answer form the API
      // The upload is complete
      progress.complete();
    }
  });

所以在这里我可以订阅事件和它的工作很好,但我也希望服务器发回的响应数据。有没有办法订阅事件和数据对象。请帮助!

dgtucam1

dgtucam11#

只需使用:

import { forkJoin, of } from 'rxjs';
...

forkJoin({
      a: this.httpservice1.(params).pipe(catchError(error => of(error))),
      b: this.httpservice2.(params).pipe(catchError(error => of(error))),
      c: this.httpservice3.(params).pipe(catchError(error => of(error))),
}).subscribe(({ a, b, c }) => 
var aux = a.body.info
})

ForkJoin将等待所有请求完成后再运行订阅

相关问题