我正在使用离子3和firebase。我正在尝试使用每个循环一次上传多个图像。上传后我需要获取下载URL将它们存储在数据库中。自从获取"下载URL"部分是异步的,我必须在图像上传的.then()部分后将数据插入数据库....我怎么能这样做?这是我提交表单后到目前为止所得到的:
post_news(form: NgForm){
this.title = form.value.title;
this.content = form.value.content;
this.category = form.value.category;
console.log(this.capturedimage1);
if(this.capturedimage1 !== ''){
this.images_to_upload.push(this.capturedimage1);
}
if(this.capturedimage2 !== ''){
this.images_to_upload.push(this.capturedimage2);
}
if(this.capturedimage3 !== ''){
this.images_to_upload.push(this.capturedimage3);
}
if(this.capturedimage4 !== ''){
this.images_to_upload.push(this.capturedimage4);
}
images_url_from_db = [];
this.images_to_upload.forEach(function(item){
let storageRef = firebase.storage().ref();
const filename = Math.floor(Date.now() / 1000);
const imageRef = storageRef.child(`images/${filename}.jpg`);
imageRef.putString(item, firebase.storage.StringFormat.DATA_URL).then(data=>{
images_url_from_db.push(downloadURL);
});
})
}
答案 0 :(得分:1)
可能对那里的人有用...经过很长一段时间的游戏后,我找到了一种方法来做到这一点......首先我将非图像数据插入到数据库中(标题,内容,类别) )。然后我得到插入数据的密钥。然后我使用密钥逐个上传图像,这将插入图像URL作为image1,image2,image3等...
post_news(form: NgForm){
this.title = form.value.title;
this.content = form.value.content;
this.category = form.value.category;
this.news = this.afDb.list('/news');
this.news.push({title: this.title,content: this.content, category: this.category}).then(data=>{
var item_key = data.key;
console.log(data.key);
if(this.capturedimage1 !== ''){
let storageRef = firebase.storage().ref();
const filename = Math.floor(Date.now() / 1000);
const imageRef = storageRef.child(`images/${filename}.jpg`);
imageRef.putString(this.capturedimage1, firebase.storage.StringFormat.DATA_URL).then(data=>{
this.news = this.afDb.list('/news');
this.news.update(item_key, {image1: data.downloadURL});
});
}
if(this.capturedimage2 !== ''){
let storageRef = firebase.storage().ref();
const filename = 'img'+Math.floor(Date.now() / 1000);
const imageRef = storageRef.child(`images/${filename}.jpg`);
imageRef.putString(this.capturedimage2, firebase.storage.StringFormat.DATA_URL).then(data=>{
this.news = this.afDb.list('/news');
this.news.update(item_key, {image2: data.downloadURL});
});
}
}).then(data=>{
form.reset();
this.capturedimage1 = '';
this.capturedimage2 = '';
this.navCtrl.parent.select(0);
});
}