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

相关内容

热门资讯

科技分享!微扑克微乐辅助,佛手... 科技分享!微扑克微乐辅助,佛手大菠萝13道挂哪里,详细教程(有挂软件)1、玩家可以在佛手大菠萝13道...
重大推荐!poker worl... 这是一款非常优秀的wepoker网页版透视方法 ia辅助检测软件,能够让你了解到wepoker网页版...
热点讨论!拱趴大菠萝挂怎么安装... 热点讨论!拱趴大菠萝挂怎么安装,wepoker黑侠破解,AI教程(有挂方法)1、玩家可以在拱趴大菠萝...
我来向大家传授!aapoker... 我来向大家传授!aapoker破解侠是真的吗,wepokerplus作弊,玩家教你(有挂神器)1、玩...
玩家必用!德州局怎么透视,we... 1、玩家必用!德州局怎么透视,wepoker免费透视脚本,2025新版教程(有挂技巧)。2、wepo...
发现玩家!pokemmo脚本最... 发现玩家!pokemmo脚本最新版,wepoker-h5下载,AI教程(有挂神器)是一款可以让一直输...
重大通报!wepoker私人局... 重大通报!wepoker私人局辅助挂,线上德州的辅助器是什么,必备教程(有挂技巧);小薇(透视辅助)...
揭秘真相!德州局透视脚本免费版... 揭秘真相!德州局透视脚本免费版下载手机版,pokemmo免费脚本,安装教程(有挂神器);德州局透视脚...
一起来探讨!wepoker私人... 一起来探讨!wepoker私人局怎么玩,德州圈脚本,AI教程(有挂教程);科技安装教程;136704...
重要通知!德普之星透视辅助软件... 1、重要通知!德普之星透视辅助软件,hhpoker辅助软件下载,扑克教程(有挂透明)。2、德普之星透...