繁体   English   中英

Angular2和xhr EventListener

[英]Angular2 and xhr EventListener

如何访问addEventListener函数中的HTML元素? 或者我可以为此函数中的组件属性设置值吗? 我想上传文件的进度百分比。 在此输入图像描述

sample.component.ts:

import {Component} from '@angular/core';
@Component({
selector: 'Account-Management',
templateUrl: 'AddUser.template.html',
})
export class AddUserComponent {
host: string = "http://" + window.location.hostname + (location.port ? ':' + location.port : '');
URL = this.host + '/api/apiUser/Upload';

 upload() {
    this.makeFileRequest(this.URL, [], this.filesToUpload).then((result) => {
        console.log(result);
    }, (error) => {
        console.error(error);
    });
}

fileChangeEvent(fileInput: any) {
    this.filesToUpload = <Array<File>>fileInput.target.files;
}
percent = "0";
makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
    var i = 1;

    return new Promise((resolve, reject) => {
        var formData: any = new FormData();
        var xhr = new XMLHttpRequest();
        for (var i = 0; i < files.length; i++) {
            formData.append("uploads[]", files[i], files[i].name);
        }
  xhr.upload.addEventListener("progress", this.progressFunction, false);  
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                if (xhr.status == 200) {
                    resolve(JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        }
        xhr.open("POST", url, true);
        xhr.send(formData);
    });
}

progressFunction(evt, d) {

    if (evt.lengthComputable) {
//percent changed but I couldn't see change in html.
        this.percent = Math.round(evt.loaded / evt.total * 100) + "%";
//log works correctly.
        console.log("PERCENT : ", this.percent);
//log works correctly.
        console.log(Math.round(evt.loaded / evt.total * 100) + "%");
    }
}

AddUser.template.html:

                <div class="form-group">
                    <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
                    <button type="button" (click)="upload()">Upload</button>
                    <span>{{percent}}</span>

                </div>

在此输入图像描述

你失去了背景。 尝试使用箭头函数,如下所示:

xhr.upload.addEventListener("progress", (evt) => this.progressFunction(evt), false);

另请参见https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM