无法读取属性' fileChangeEvent'未定义在Angular2中

时间:2017-01-02 14:01:25

标签: node.js angular

选择图像文件时出现此错误

  import {Injectable} from '@angular/core';

@Injectable()
export class UploadPhotoService {
  filesToUpload: Array<File>;

    constructor() {
        this.filesToUpload = [];
    }

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

    fileChangeEvent(fileInput: any){
        this.filesToUpload = <Array<File>> fileInput.target.files;
    }

    makeFileRequest(url: string, params: Array<string>, files: Array<File>) {
        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.onreadystatechange = function () {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                      alert("Upload successful!");
                    } else {
                        reject(xhr.response);
                    }
                }
            }
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Authorization", "Bearer "+localStorage.getItem("token"));
            xhr.send(formData);
        });
    }
}



     <div class="field">
  <label>Upload Photo</label>
  <input type="file" (change)="uploadPhotoService.fileChangeEvent($event)" />
  <button type="button" (click)="uploadPhotoService.upload()" class="ui mini button">Upload</button>

  </div>

选择图像文件后显示上述错误,是否还有其他方法可以在angular2上传图像文件..请帮忙,并给出EXCEPTION:./AddAdvertComponent类中的错误AddAdvertComponent - 内联模板:30: 2引起:无法读取属性&#39; fileChangeEvent&#39;未定义的

 ORIGINAL EXCEPTION: Cannot read property 'fileChangeEvent' of undefined

1 个答案:

答案 0 :(得分:0)

抛出错误

  

ORIGINAL EXCEPTION:无法读取未定义的属性'fileChangeEvent'

因为您未正确地致电fileChangeEvent或您的uploadPhotoService没有定义,所以您必须像这样打电话

如果方法属于同一类

 <input type="file" (change)="fileChangeEvent($event)" />

或者你的方法是在某个不同的类或某个服务中,而不是确保你在构造函数中启动该服务,如下所示

constructor(prive uploadPhotoService: UploadPhotoService) { }

比你能够像这样使用

<input type="file" (change)="uploadPhotoService.fileChangeEvent($event)" />