如何解决:TypeError:无法将未定义或空转换为对象
2016-09-28
14135
我正在创建一个 angular2 项目,并使用 ng2-uploader 作为文件上传插件。我想拖放到一个 div 上,同时在 div 内添加一个上传按钮。选择要上传的文件后,我收到错误 TypeError:无法将未定义或 null 转换为对象 。
Html 代码为:
<div [hidden]="!onUpload" ngFileDrop [options]="options" (onUpload)="handleUpload($event)" [ngClass]="{'file-over': hasBaseDropZoneOver}" (onFileOver)="fileOverBase($event)">
<input type="file" ngFileSelect [options]="options" (onUpload)="handleUpload($event)">
<p><span>Response: {{ uploadFile | json }}</span></p>
</div>
组件为:
import { Component, OnInit, NgModule, NgZone } from '@angular/core';
@Component({
selector: 'app-fileselect',
templateUrl: './fileselect.component.html',
styleUrls: ['./fileselect.component.css']
})
export class FileSelectComponent implements OnInit {
zone: NgZone;
hasBaseDropZoneOver: boolean = false;
basicProgress: number = 0;
uploadFile: any;
constructor() {
this.zone = new NgZone({ enableLongStackTrace: false });//file upload
}
options: Object = {
url: 'http://localhost:4200/assets/documents'
};
handleUpload(data): void {
if (data && data.response) {
data = JSON.parse(data.response);
this.uploadFile = data;
this.zone.run(() => {
this.basicProgress = data.progress.percent;
});
}
}
fileOverBase(e: any): void {
this.hasBaseDropZoneOver = e;
}
}
2个回答
响应:{{ uploadFile | json } }
由于此结构,您会收到此错误,当您使用输入文件上传项目时,它将自动触发父 div ('ngFileDrop')。因此它将使用空数据调用该函数。此过程将导致错误。
因此,您可以做一件事,只需将输入按钮放在父 div 之外并尝试。它肯定会起作用。
<div [hidden]="!onUpload" ngFileDrop [options]="options" (onUpload)="handleUpload($event)" [ngClass]="{'file-over': hasBaseDropZoneOver}" (onFileOver)="fileOverBase($event)">
<p><span>Response: {{ uploadFile | json }}</span></p>
</div>
<input type="file" ngFileSelect [options]="options" (onUpload)="handleUpload($event)">
现在,您可以使用一些 css 将输入按钮定位在 div 内。
只需检查一下。
Aswin KV
2016-10-05
在您的 html 代码中,选项后面缺少一个
"
:
您写道:
<input type="file" ngFileSelect [options]="options (onUpload)="handleUpload($event)">
您应该这样写:
<input type="file" ngFileSelect [options]="options" (onUpload)="handleUpload($event)">
StephaneM
2016-09-28