首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular2和xhr EventListener

Angular2和xhr EventListener
EN

Stack Overflow用户
提问于 2016-05-15 08:43:06
回答 1查看 1.1K关注 0票数 3

如何访问addEventListener函数中的HTML元素?或者可以在此函数中设置组件属性的值吗?我想取得进步百分之上传文件。

sample.component.ts :

代码语言:javascript
复制
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 :

代码语言:javascript
复制
                <div class="form-group">
                    <input type="file" (change)="fileChangeEvent($event)" placeholder="Upload file..." />
                    <button type="button" (click)="upload()">Upload</button>
                    <span>{{percent}}</span>

                </div>

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-05-15 08:48:37

你失去了背景。尝试使用这样的箭头函数:

代码语言:javascript
复制
xhr.upload.addEventListener("progress", (evt) => this.progressFunction(evt), false);

另见functions

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37236188

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档