我正在使用
我想要实现的目标
上传项目详情时,我想知道是否选择了图片。
如果没有,请从服务中调用其他方法并指定默认图像
如果是,请使用图片
问题
我可能正在接近这个错误,但我想要执行此逻辑的方式是看用户是否选择了“选择图像”。 (输入类型文件)。如果已选择图像,则' if(文件)'似乎注册正常,如果没有选择图像,则会出现以下错误:
ProjectsAddComponent.html:71 ERROR TypeError:无法读取属性' item'未定义的
项目添加HTML
<div class="vs__upload__container">
<input type="file" id="file-1" class="inputfile inputfile-1" (change)="detectFiles($event)" />
<label class="vs__upload__button" for="file-1">
<i class="fa fa-upload" aria-hidden="true"></i>
<span>Choose a file…</span>
</label>
</div>
<div class="vs__details__actions">
<button class="vs__button" (click)="addNewProject(newTitle.value, newReference.value, newDate.value); newTitle.value='';
newReference.value=''; newDate.value='';">
Add
</button>
</div>
&#13;
项目添加组件TS
请参阅&#39; addNewProject&#39;函数if语句
import { Component, OnInit } from '@angular/core';
import { ProjectsAddService } from './projects-add.service';
import { Upload } from './upload';
import * as _ from "lodash";
@Component({
selector: 'upload-form',
templateUrl: './projects-add.component.html',
styleUrls: ['./projects-add.component.css']
})
export class ProjectsAddComponent {
selectedFiles: FileList;
currentUpload: Upload;
constructor(private upSvc: ProjectsAddService) { }
detectFiles(event) {
this.selectedFiles = event.target.files;
}
uploadSingle() {
let file = this.selectedFiles.item(0)
this.currentUpload = new Upload(file);
}
addNewProject(title: string, reference: string, date: string) {
let file = this.selectedFiles.item(0)
this.currentUpload = new Upload(file);
if (file) {
console.log('this is the file = ', file);
// Call method in service to include the upload file
this.upSvc.addNewProjectWithImage(title, reference, date, this.currentUpload);
} else {
console.log('no file');
this.upSvc.addNewProjectWithOutImage(title, reference, date);
}
}
}
&#13;
答案 0 :(得分:1)
您需要检查是否已选择任何文件。您的代码可能会抛出未定义的异常。
addNewProject(title: string, reference: string, date: string)
{
// Check if an image file has been selected
if(this.selectedFiles && this.selectedFiles.length > 0) {
let file = this.selectedFiles.item(0);
this.currentUpload = new Upload(file);
console.log('this is the file = ', file);
// Call method in service to include the upload file
this.upSvc.addNewProjectWithImage(title, reference, date, this.currentUpload);
}
// otherwise call the method with default image.
else {
console.log('no file');
this.upSvc.addNewProjectWithOutImage(title, reference, date);
}
}
检查uploadSingle
方法中的相同条件。
uploadSingle() {
if(this.selectedFiles && this.selectedFiles.length > 0) {
let file = this.selectedFiles.item(0);
this.currentUpload = new Upload(file);
}
}