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

问题描述 投票:1回答:1

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

首先,进度事件只被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.`);
          }
        });

进步行为是,

enter image description here

angular file-upload upload angular-httpclient angular-httpclient-interceptors
1个回答
2
投票

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

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

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

还引用了该文件:

// HttpClient.request API生成原始事件流

//包括开始(已发送),进度和响应事件。

顺便说一句,将上传进度处理放在HttpInterceptor中并不是一个好习惯,因为它的效果是项目范围的,即你所做的每个请求都将通过拦截器。而且你不需要在每个请求中处理进度,或者你呢?

© www.soinside.com 2019 - 2024. All rights reserved.