码迷,mamicode.com
首页 > 数据库 > 详细

[Angular] Provide Feedback to Progress Events with Angular’s HttpRequest Object

时间:2018-02-14 21:32:56      阅读:261      评论:0      收藏:0      [点我收藏+]

标签:rom   from   hat   int   tar   ide   ack   users   ota   

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

  }

 

 

 

[Angular] Provide Feedback to Progress Events with Angular’s HttpRequest Object

标签:rom   from   hat   int   tar   ide   ack   users   ota   

原文地址:https://www.cnblogs.com/Answer1215/p/8448909.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!