更新上传文件的引导进度条有角度2

时间:2016-10-08 13:14:22

标签: javascript angular rxjs

我希望根据this question显示用户上传文件时进度条的进度。这是我的代码:

服务:

public makeFileRequest(url: string, files: File): Observable<Models.MalFile> {

    return  Observable.create ((Observable) => {
        var formData: any = new FormData();
        var xhr = new XMLHttpRequest();
        console.log(files[0]);

        // for(var i = 0; i < files.length; i++) {
             formData.append("file", files[0], files[0].name);
        // }
        xhr.onreadystatechange =  () => {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    Observable.next(JSON.parse(xhr.response));
                    Observable.complete();
                } else {
                    Observable.error(xhr.response);
                    alert(xhr.response);
                }
            }
        }
        xhr.upload.onprogress = (event) => {
          this.progress = Math.round( event.loaded / event.total * 100);
          this.progressObserver.next(this.progress);
        }
        xhr.open("POST", url, true);
        xhr.send(formData);
    });
}

和我的组件:

ngOnInit() {

this.service.progress.subscribe(
  data => {
    this.loadedData = data;
    console.log("data:",this.loadedData);
    //this.loadedData.bind(data)  ;
  },
  (error) => {
    console.log('Could not to upload file');

  },

  () => {
    // this.loadedData = 100;
  }

)}

我想将loadedData绑定到进度条视图,但此时我在控制台中记录进度:

upload log screen shot

我的问题是:

将Observable对象绑定到视图中的进度条值:

              <div class="progress" style="">
                <progress dir="ltr" class="progress progress-success active progress-striped progress-animated" value="{{loadedData}}" max="100">  </progress>
              </div>

此代码只显示上传完成时的进度条(100%)!

如何将loadedData绑定到进度条值?

1 个答案:

答案 0 :(得分:1)

我认为this.loadedData可以获得您想要的正确数据。然后继续,

<div class="progress" style="">
     <progress dir="ltr" 
               class="progress progress-success active progress-striped progress-animated" 
               value="loadedData"      //<<<===removed {{ }} curly braces.
               max="100">  
      </progress> 
</div>