代码之家  ›  专栏  ›  技术社区  ›  JSON

可以在httpinterceptor中获取上载进度事件,但不能从httpclient调用中获取?

  •  1
  • JSON  · 技术社区  · 7 年前

    我正在使用 httpinterceptor 并且我有一个HTTP服务,它调用运行httpclient的HTTP方法。我正在努力获得上传的进度,我在这里面临两个问题,

    首先,进度事件只被 httpinterceptor 捕获,而不是我的服务中的任何HTTP调用方方法。看起来前者掩盖了进度报告。

    其次,进度值始终以100%开始,它开始递增。

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

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

    my httpinterceptor service looks like,,

    if(req.url.search('https')<0){
    const headers=新的httpheaders({
    accept:'应用程序/json',
    授权:`bearer$this.authservice.gettoken()`,
    'x-xsrf-token':`$this.authservice.getAntiforgeryToken()`,
    clientTimeZoneOffst:`$new date().getTimeZoneOffset()`,
    clientTimeZoneID:intl.datetimeformat().resolvedOptions().TimeZone,
    clinetloginid:`$this.authservice.getloginid()`,
    })(二)
    const clone req=req.clone(headers);
    返回next.handle(clonereq).pipe(
    mergemap((ev:httpevent<any>)=>。{
    如果(ev.type==httpeventtype.uploadProgress){
    const percentdone=数学四舍五入((100*ev.loaded)/ev.total);
    console.log(`file is$percentdone%uploaded.`);
    }
    此.httpResponseHandlerService.handleSuccessResponse(ev);
    返回(ev)的可观测值;
    }),请
    catchError(错误=>){
    此.httpResponseHandlerService.handleErrorResponse(错误,请求);
    返回observable.throw(错误);
    }),请
    )(二)
    }其他{
    返回next.handle(req);
    }
    }
    

    我的HTTP调用程序服务,

    public upload<t>(apiURL:string,jsondata:=))。{
    返回this.httpservice.post<t>(this.baseurl+apiurl,jsondata,){
    报告进度:正确,
    })(二)
    }
    

    我试图取得进展的方法是,

    this.httpservice
    .upload(this.api+this.id.value,数据)
    .takeuntil(this.unsubscribe)
    .subscribe((ev:httpevent<any>)=>//这里什么都没有发生!
    如果(ev.type==httpeventtype.uploadProgress){
    const percentdone=数学四舍五入((100*ev.loaded)/ev.total);
    console.log(`file is$percentdone%uploaded.`);
    }
    })(二)
    

    进度行为是,

    .

    首先,进度事件仅被捕获高温拦截器我的服务中没有任何HTTP调用方方法。看起来前者掩盖了进度报告。

    第二,进度值总是以100%开始,它开始递增。

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

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

    我的高温拦截器服务看起来,

    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.`);
              }
            });
    

    进度行为是,

    1 回复  |  直到 6 年前
        1
  •  2
  •   Envil    6 年前

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

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

    http.post 只是执行正常HTTP请求的快捷方式 http.request .对于完整的请求创建选项,例如当我们希望下载或上载进度跟踪时,您应该使用 HTTP.请求 (手动创建带有许多选项的请求对象,然后执行它)。

    另引自文件:

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

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

    顺便说一下,把上传进度处理放在httpinterceptor中并不是一个好的实践,因为它的效果是项目范围的,即你提出的每一个请求都会通过interceptor。您不需要在每个请求中处理进度,还是?