zoukankan      html  css  js  c++  java
  • [Angular] Provide Feedback to Progress Events with Angular’s HttpRequest Object

    In some cases your application might need to upload large amounts of data, such as files. Obviously for a good UX we should provide the user some feedback on the progress of the upload. Angular’s HttpRequest object has a property reportProgress which allows us to do exactly that. Let’s see how.

    // service:
    import { Injectable } from '@angular/core';
    import { Observable } from 'rxjs/Observable';
    import { HttpClient, HttpRequest, HttpEvent } from '@angular/common/http';
    
    export interface Person {
      name: string;
    }
    
    @Injectable()
    export class PeopleService {
    
      constructor(private http: HttpClient) {}
    
      uploadAvatar(data): Observable<HttpEvent<Object>> {
        const req = new HttpRequest(
          'POST',
          'https://reqres.in/api/users/1',
          data,
          { reportProgress: true }
        );
    
        return this.http.request(req);
      }
    
    }
    // Component
      import { HttpClient, HttpRequest, HttpEvent, HttpEventType } from '@angular/common/http';
    
    
      uploadAvatar(fileUpload) {
        const formData = new FormData();
        formData.append('avatar', fileUpload.files[0], 'avatar.jpg');
    
        this.peopleService
          .uploadAvatar(formData)
          .subscribe(res => {
            if (res.type === HttpEventType.UploadProgress) {
              const percentage = Math.round(100 * res.loaded / res.total);
    
              this.output = `File is ${percentage}% uploaded`;
            } else if (res instanceof HttpResponse) {
              this.output = `File is completely uploaded`;
            }
          });
    
      }

  • 相关阅读:
    Django的mode的分组查询和聚合查询和F查询和Q查询
    Django的models操作
    django复习--学校管理系统用到的知识点梳理
    django做form表单的数据验证
    一个不错的git资源站点
    php异常处理
    laravel自定义验证
    docker从容器中怎么访问宿主机
    laravel 之jwt认证使用详解
    laravel更改默认的登录密码加密方式
  • 原文地址:https://www.cnblogs.com/Answer1215/p/8448909.html
Copyright © 2011-2022 走看看