可以在 HttpInterceptor 中获取上传进度事件,但不能从 HttpClient 调用中获取?

Can get upload progress event in HttpInterceptor but not from HttpClient call?

我正在使用 HttpInterceptor 并且我有一个调用 http 方法的 Http 服务 运行 HttpClient。我正在尝试获取上传进度,但我在这里遇到两个问题,

首先,进度事件仅被 HttpInterceptor 捕获,而不是我服务中的任何 Http 调用方法。看起来前者正在掩盖进度报告。

其次,进度值总是从100%开始,开始递增。

我正在延迟加载我的模块,HttpInterceptor 在 app.module 级别注册。

如何从 http 方法获取进度值?

我的 HttpInterceptor 服务看起来像,

if (req.url.search('https') < 0) {
      const headers = new HttpHeaders({
        Accept: 'application/json',
        Authorization: `Bearer ${this.authService.getToken()}`,
        'X-XSRF-TOKEN': `${this.authService.getAntiforgeryToken()}`,
        ClientTimeZoneOffest: `${new Date().getTimezoneOffset()}`,
        ClientTimeZoneId: Intl.DateTimeFormat().resolvedOptions().timeZone,
        ClinetLogInId: `${this.authService.getLogInId()}`,
      });
      const cloneReq = req.clone({ headers });
      return next.handle(cloneReq).pipe(
        mergeMap((ev: HttpEvent<any>) => {
          if (ev.type === HttpEventType.UploadProgress) {
            const percentDone = Math.round((100 * ev.loaded) / ev.total);
            console.log(`File is ${percentDone}% uploaded.`);
          }
          this.httpResponseHandlerService.handleSuccessResponse(ev);
          return Observable.of(ev);
        }),
        catchError(error => {
          this.httpResponseHandlerService.handleErrorResponse(error, req);
          return Observable.throw(error);
        }),
      );
    } else {
      return next.handle(req);
    }
  }

我的 Http 调用服务,

public upload<T>(apiUrl: string, jsonData: {} = {}) {
    return this.httpService.post<T>(this.baseUrl + apiUrl, jsonData, {
      reportProgress: true,
    });
  }

我试图取得进展的方法就像,

this.httpService
        .upload(this.api + this.id.value, data)
        .takeUntil(this.unsubscribe)
        .subscribe((ev: HttpEvent<any>) => { // Nothing is happening here!
          if (ev.type === HttpEventType.UploadProgress) {
            const percentDone = Math.round((100 * ev.loaded) / ev.total);
            console.log(`File is ${percentDone}% uploaded.`);
          }
        });

进度行为是,

您执行请求的方式不正确,请参考http://angular.io/guide/http#listening-to-progress-events

您应该创建一个 HttpRequest 然后调用 this.http.request(req) 而不是 this.http.post(...)

http.post只是http.request执行普通http请求的简写。对于完整的请求创建选项,比如当我们想要下载或上传进度跟踪时,您应该使用 http.request(您手动创建具有许多选项的请求对象,然后执行它)。

也引用自文档:

// The HttpClient.request API produces a raw event stream

// which includes start (sent), progress, and response events.

顺便说一句,将上传进度处理放在 HttpInterceptor 中并不是一个好的做法,因为它的效果是整个项目范围的,即您发出的每个请求都会通过拦截器。而且您不需要在每个请求中都进行进度处理,对吗?