Angular监听网络调用(下载功能)的开始和完成,以显示进度条或旋转器。
创始人
2024-10-26 21:01:11
0

在Angular中,你可以使用HttpClient来发送网络请求,并通过HttpEventprogress事件来监听请求的进度。下面是一个示例代码,展示了如何在下载文件时显示进度条或旋转器:

  1. 首先,创建一个服务来处理网络请求:
import { Injectable } from '@angular/core';
import { HttpClient, HttpRequest, HttpEventType, HttpResponse } from '@angular/common/http';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class DownloadService {

  constructor(private http: HttpClient) { }

  downloadFile(url: string): any {
    const req = new HttpRequest('GET', url, {
      reportProgress: true,
      responseType: 'blob'
    });

    return this.http.request(req).pipe(
      map((event) => {
        if (event.type === HttpEventType.DownloadProgress) {
          const progress = Math.round(100 * event.loaded / event.total);
          return { type: 'progress', value: progress };
        } else if (event instanceof HttpResponse) {
          return { type: 'success', value: event.body };
        }
      })
    );
  }
}
  1. 接下来,在组件中使用该服务,并监听请求的进度:
import { Component } from '@angular/core';
import { DownloadService } from './download.service';

@Component({
  selector: 'app-download',
  template: `
    
` }) export class DownloadComponent { showProgress = false; progress = 0; constructor(private downloadService: DownloadService) { } download() { this.showProgress = true; const url = 'https://example.com/file.pdf'; // 替换为你的文件下载链接 this.downloadService.downloadFile(url).subscribe((event: any) => { if (event.type === 'progress') { this.progress = event.value; } else if (event.type === 'success') { this.showProgress = false; // 处理下载完成后的文件 const fileBlob: Blob = event.value; const fileUrl = URL.createObjectURL(fileBlob); window.open(fileUrl); // 在新窗口中打开文件 } }); } }
  1. 最后,在进度条组件中显示进度:
import { Component, Input } from '@angular/core';

@Component({
  selector: 'progress-bar',
  template: `
    
{{ progress }}%
` }) export class ProgressBarComponent { @Input() progress: number; }

这样,当用户点击“下载文件”按钮时,进度条或旋转器将显示下载进度。完成后,文件将在新窗口中打开。你可以根据需要自定义进度条或旋转器的样式。

相关内容

热门资讯

安装apache-beam==... 出现此错误可能是因为用户的Python版本太低,而apache-beam==2.34.0需要更高的P...
避免在粘贴双引号时向VS 20... 在粘贴双引号时向VS 2022添加反斜杠的问题通常是由于编辑器的自动转义功能引起的。为了避免这个问题...
Android Recycle... 要在Android RecyclerView中实现滑动卡片效果,可以按照以下步骤进行操作:首先,在项...
omi系统和安卓系统哪个好,揭... OMI系统和安卓系统哪个好?这个问题就像是在问“苹果和橘子哪个更甜”,每个人都有自己的答案。今天,我...
原生ios和安卓系统,原生对比... 亲爱的读者们,你是否曾好奇过,为什么你的iPhone和安卓手机在操作体验上有着天壤之别?今天,就让我...
Android - 无法确定任... 这个错误通常发生在Android项目中,表示编译Debug版本的Java代码时出现了依赖关系问题。下...
Android - NDK 预... 在Android NDK的构建过程中,LOCAL_SRC_FILES只能包含一个项目。如果需要在ND...
Akka生成Actor问题 在Akka框架中,可以使用ActorSystem对象生成Actor。但是,当我们在Actor类中尝试...
Agora-RTC-React... 出现这个错误原因是因为在 React 组件中使用,import AgoraRTC from “ago...
Alertmanager在pr... 首先,在Prometheus配置文件中,确保Alertmanager URL已正确配置。例如:ale...