我有两个函数 updateSpeaker(), uploadSpeakerImageAdd()我想将图像上传到webapi并获取文件名作为回调,我想发布文件名在 updateSpeaker()。
中updateSpeaker()
updateSpeaker(menuItem)
{
this.uploadSpeakerImageAdd();
console.log(this.imagename)
let update_event_speakers_body={
'_id':this.menuItem.id,
'name':this.menuItem.name,
'matter':this.menuItem.matter,
'image':this.imagename, //file name getting from the uploadSpeakerImageAdd().
'session':this.menuItem.session,
'link':this.menuItem.link,
'event_id':this.EventId };
this.getPostMenuService.doUpdateSpeakers(update_event_speakers_body).subscribe(
data => {
console.log(data);
},err => {
console.log("error")
});
}
uploadSpeakerImageAdd()
uploadSpeakerImageAdd() {
let inputEl: HTMLInputElement = this.inputEl.nativeElement;
let fileCount: number = inputEl.files.length;
console.log(fileCount);
let formData = new FormData();
if (fileCount > 0) { // a file was selected
for (let i = 0; i < fileCount; i++) {
formData.append('file[]', inputEl.files.item(i));
}
this.getPostMenuService.doPostImage( formData).subscribe(data => {
this.imagename=data.file;
console.log( this.imagename);
},
err => {
console.log("error")
});
}
}
此代码正常运行但仅在执行 updateSpeaker()后获取文件名
答案 0 :(得分:0)
您需要将函数作为参数传递给uploadSpeakerImageAdd()
updateSpeaker(menuItem){
this.uploadSpeakerImageAdd(function(imageName){
// You get file name here so create the body object and do Post call.
});
}
您将传递匿名函数作为回调到uploadSpeakerImageAdd
函数。
uploadSpeakerImageAdd(callback) {
// perform all the logic before post call
this.getPostMenuService.doPostImage( formData).subscribe(data => {
// Pass the image name to callback
callback(data.file);
},
err => {
console.log("error")
});
如果你喜欢使用反应式编程,它将是这样的:
updateSpeaker(menuItem){
this.uploadSpeakerImageAdd()
.subscribe(file => {
// you get the file object, create the body and do Post call
});
}
在uploadSpeakerImageAdd
方法内部,您只需返回observable:
uploadSpeakerImageAdd() {
// perform all the logic before post call
return this.getPostMenuService.doPostImage( formData);
}
答案 1 :(得分:0)
从你的html部分,火灾变化事件如下:
<input type="file" (change)="uploadSpeakerImageAdd($event)" value="file">
And in your component or controller:
uploadSpeakerImageAdd($event): void {
let inputValue: any;
inputValue = $event.target;
this.file = inputValue.files[0];
this.getPostMenuService.doPostImage(this.file)
.subscribe(
data => {
this.imagename=data.file;
},
error => {
};
});
}
在change
事件中调用您的uploadSpeakerImageAdd。