Angular 6进度条服务

时间:2018-05-25 11:08:30

标签: angular progress-bar angular6

尝试构建进度服务,以了解文件的总数和加载百分比。我在下面写了这个服务并在提供者部分注册;

import { Injectable } from '@angular/core';
import { Subject, BehaviorSubject } from 'rxjs/Rx'
import { BrowserXhr } from '@angular/http';

@Injectable()
export class ProgressService {
  uploadProgress = new Subject<any>();
  downloadProgress = new Subject<any>();

}


@Injectable()
export class BrowserXhrWithProgress extends BrowserXhr {

  constructor(private service: ProgressService) {
    super();
  }
  build(): XMLHttpRequest {
    var xhr: XMLHttpRequest = super.build();
    xhr.onprogress = (event) => {
      this.service.downloadProgress.next(this.createProgress(event));
    };

    xhr.upload.onprogress = (event) => {
      this.service.uploadProgress.next(this.createProgress(event));
    };
    return xhr;
  }

  private createProgress(event: any) {
    return {
      total: event.total,
      percentage: Math.round((event.loaded / event.total) * 100)
    };
  }
}

我在加载文件之前订阅了服务;

this.progressService.uploadProgress.subscribe(progress => { console.log(progress) });

但无法在控制台中记录任何内容。

  { provide: BrowserXhr, useClass: BrowserXhrWithProgress },
   ProgressService

任何想法都很有用。

0 个答案:

没有答案