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

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

  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; }

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

相关内容

热门资讯

前端-session、jwt 目录:   (1)session (2&#x...
linux入门---制作进度条 了解缓冲区 我们首先来看看下面的操作: 我们首先创建了一个文件并在这个文件里面添加了...
关于测试,我发现了哪些新大陆 关于测试 平常也只是听说过一些关于测试的术语,但并没有使用过测试工具。偶然看到编程老师...
前缀和与对数器与二分法 1. 前缀和 假设有一个数组,我们想大量频繁的去访问L到R这个区间的和,...
nodejs:本地安装nvm实... 一、背景-使用不同版本node的原因 vue3+ts、nuxt3版本,node...
JAVA集合知识整理 Java集合知识整理 HashMap相关 HashMap的底层数据结构:jdk1.8之...
无刷直流电机介绍及单片机控制实... 无刷直流电机介绍及单片机控制实例前言基本概念优势与劣势使用寿命基本结构使用单片机控制实例电子调速器&...
fwdiary(2) dp2 1.传纸条  AcWing 275. 传纸条 - AcWing 走两条路,走一条最大的...
常用的DOS命令 常用的DOS命令 DOS(Disk Operating System,磁...
<C++> 类和对象(下) 1.const成员函数将const修饰的“成员函数”称之为const成员函数,cons...