Angular中的HTTP ProgressEvent仅在HTTP拦截器中跟踪,并不在实际的API调用中跟踪。
创始人
2024-10-31 06:00:13
0

在Angular中,HTTP ProgressEvent只能在HTTP拦截器中跟踪,并不会在实际的API调用中跟踪。这是因为HTTP拦截器会在请求和响应之间进行操作。

下面是一个示例解决方法,展示如何在HTTP拦截器中跟踪ProgressEvent:

  1. 创建一个名为progress.interceptor.ts的新文件,并在其中添加以下代码:
import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse } from '@angular/common/http';
import { Observable } from 'rxjs';
import { tap } from 'rxjs/operators';

@Injectable()
export class ProgressInterceptor implements HttpInterceptor {
  intercept(req: HttpRequest, next: HttpHandler): Observable> {
    const clonedRequest = req.clone({ reportProgress: true }); // 克隆请求并启用进度报告

    return next.handle(clonedRequest).pipe(
      tap((event: HttpEvent) => {
        if (event.type === HttpEventType.DownloadProgress) {
          const percentDone = Math.round((100 * event.loaded) / event.total);
          console.log(`File is ${percentDone}% downloaded.`);
        } else if (event instanceof HttpResponse) {
          console.log('Request completed.'); // 请求完成时的处理
        }
      })
    );
  }
}
  1. 在你的app.module.ts文件中注册HTTP拦截器。找到providers数组,并将ProgressInterceptor添加到其中:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';

import { AppComponent } from './app.component';
import { ProgressInterceptor } from './progress.interceptor';

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule, HttpClientModule],
  providers: [
    {
      provide: HTTP_INTERCEPTORS,
      useClass: ProgressInterceptor,
      multi: true,
    },
  ],
  bootstrap: [AppComponent],
})
export class AppModule {}

现在,当你发起API调用时,HTTP拦截器将会跟踪ProgressEvent并在控制台输出相应的信息。请记住,在实际的API调用中,并不会直接跟踪ProgressEvent,而是通过HTTP拦截器进行跟踪。

相关内容

热门资讯

出乎意料的是!大当家辅助脚本设... 出乎意料的是!大当家辅助脚本设置(辅助挂)一直是有挂(有挂诀窍)-哔哩哔哩《详细加薇13670430...
第2分钟开挂!吉安中至小程序辅... 第2分钟开挂!吉安中至小程序辅助,方片十三张源码,扑克教程-2026最新版本1、用户打开应用后不用登...
有了最新消息!福建兄弟十三水辅... 有了最新消息!福建兄弟十三水辅助工具(辅助挂)果然确实有挂(有挂方式)-哔哩哔哩 了解更多开挂安装加...
第九分钟开挂!来物局潮汕辅助,... 您好,广西老友玩有破解吗这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多...
近年来!江西中至黑科技辅助软件... 近年来!江西中至黑科技辅助软件(辅助挂)一贯确实有挂(有挂烘培)-哔哩哔哩 【无需打开直接搜索加薇1...
第十分钟开挂!三哥玩十三张辅助... 第十分钟开挂!三哥玩十三张辅助器,大唐撸麻雀辅助码,我来教教你-2026最新版本1、三哥玩十三张辅助...
昨日!开心泉州辅助器app下载... 昨日!开心泉州辅助器app下载(辅助挂)原来真的是有挂(有挂大纲)-哔哩哔哩 【无需打开直接搜索加薇...
第一分钟开挂!欢乐达人暗宝辅助... 第一分钟开挂!欢乐达人暗宝辅助工具,决战卡五星游戏辅助器,细节方法-2026最新版本1、任何决战卡五...
受玩家影响!黑科技辅助器(辅助... 受玩家影响!黑科技辅助器(辅助挂)原来真的是有挂(有挂绝活儿)-哔哩哔哩黑科技辅助器ai黑科技系统规...
第九分钟开挂!逍遥湖北卡五辅助... 第九分钟开挂!逍遥湖北卡五辅助,谁有老友广东辅助器,总结教程-2026最新版本1.谁有老友广东辅助器...