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

相关内容

热门资讯

透视必备!hhpoker透视工... 透视必备!hhpoker透视工具,hhpoker德州挂真的有吗(透视)竟然存在有工具(哔哩哔哩);暗...
有了最新消息!拱趴大菠萝万能挂... 有了最新消息!拱趴大菠萝万能挂图解,微乐小程序黑科技下载ios,揭幕透视(真的有挂)-哔哩哔哩1、起...
透视总结!德州局怎么透视,hh... 透视总结!德州局怎么透视,hhpoker有辅助吗(透视)原来存在有方法(哔哩哔哩)1、这是跨平台的德...
透视神器!来玩德州破解器,微乐... 透视神器!来玩德州破解器,微乐小程序怎么挂脚本,解迷透视(有挂细节)-哔哩哔哩1、完成来玩德州破解器...
透视脚本!wepoker俱乐部... 透视脚本!wepoker俱乐部辅助,微乐麻辣自建房辅助视频,分享脚本(有挂方法)-哔哩哔哩wepok...
透视普及!德州hhpoker脚... 透视普及!德州hhpoker脚本,模拟器打开hhpoker(透视)都是真的有教程(哔哩哔哩)1、玩家...
透视挂透视!hhpoker有作... 透视挂透视!hhpoker有作必弊的吗,微乐小程序黑科技,透视脚本(有挂细节)-哔哩哔哩1、hhpo...
透视辅助!hhpoker是真的... 透视辅助!hhpoker是真的假的,hh poker辅助有用吗(透视)一贯真的是有神器(哔哩哔哩)1...
透视ai代打!hhpoker透... 透视ai代打!hhpoker透视脚本,微乐自建房辅助工具安全吗,揭幕透视(有挂秘籍)-哔哩哔哩1、金...
透视有挂!wepokerplu... 透视有挂!wepokerplus万能挂,wepoker俱乐部辅助(透视)一贯有脚本(哔哩哔哩)1、任...