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拦截器进行跟踪。

相关内容

热门资讯

玩家交流!蜀山挂件辅助,创思维... 玩家交流!蜀山挂件辅助,创思维激k透视插件,详细脚本(有挂方式)运创思维激k透视插件辅助工具,进入游...
一分钟了解!老友麻将辅助器,青... 一分钟了解!老友麻将辅助器,青龙辅助3.0,详细器(有挂解密)1、老友麻将辅助器免费辅助多个强度级别...
一分钟揭秘!先锋脚本辅助,哈局... 一分钟揭秘!先锋脚本辅助,哈局辅助作弊,详细器(了解有挂)暗藏猫腻,小编详细说明先锋脚本辅助破解器有...
如何分辨真伪!丽水茶苑手机辅助... 如何分辨真伪!丽水茶苑手机辅助,蜀山四川小程序破解版,详细方法(竟然有挂)1)蜀山四川小程序破解版免...
推荐一款!UU Games辅助... 推荐一款!UU Games辅助器,江汉晃晃辅助器,详细器(揭秘有挂)亲,关键说明,江汉晃晃辅助器透视...
玩家必看科普!天天微友第三方辅... 玩家必看科普!天天微友第三方辅助软件下载,皮皮辅助器,详细器(了解有挂)1、天天微友第三方辅助软件下...
玩家必看科普!四川途游小程序辅... 玩家必看科普!四川途游小程序辅助,雀神挂件价格骗局,详细方法(有挂教学)1、四川途游小程序辅助公共底...
最新技巧!四川游戏辅助器,小程... 最新技巧!四川游戏辅助器,小程序能开挂吗,详细神器(有挂方式)1、小程序能开挂吗破解器简单,小程序能...
今日重大通报!皮皮游戏辅助平台... 今日重大通报!皮皮游戏辅助平台,火神工作室辅助大全,详细app(真是有挂)1、上手简单,内置详细流程...
一分钟揭秘!五十k辅助,微友辅... 一分钟揭秘!五十k辅助,微友辅助神器下载,详细器(有挂详细)1、微友辅助神器下载有没有辅助教程、微友...