【问题标题】:I want to save the downloaUrl of image in the database using angularfire2我想使用 angularfire2 将图像的 downloaUrl 保存在数据库中
【发布时间】:2017-09-19 04:36:51
【问题描述】:
我能够获取存储中项目的 url,但我无法将它们保存到数据库中。 item.downloadUrl 无法接收 this.imageUrl。有没有其他方法可以将项目的downloadUrl保存到数据库?
addItem(item){
// @TODO - Storage ref
let storageRef = firebase.storage().ref();
for(let selectedFile of [(<HTMLInputElement>document.getElementById('image')).files[0]]){
let path=`/${this.folder}/${selectedFile.name}`;
let iRef= storageRef.child(path);
iRef.put(selectedFile).then((snapshot)=>{
item.image=selectedFile.name;
item.path=path;
storageRef.child(item.path).getDownloadURL().then((url)=>{
//Setting Image Url below
this.imageUrl =url;
item.downloadUrl=this.imageUrl;
console.log(this.imageUrl);
});
return this.items.push(item);
}).catch((error)=>{
console.log(error);
});
}
}
【问题讨论】:
标签:
javascript
firebase
firebase-realtime-database
firebase-storage
angularfire2
【解决方案1】:
当尚未检索到下载 URL 时,您正在将项目推送到数据库。要解决此问题,请将对 databaseRef.push() 的调用移至 then:
let storageRef = firebase.storage().ref();
for(let selectedFile of [(<HTMLInputElement>document.getElementById('image')).files[0]]){
let path=`/${this.folder}/${selectedFile.name}`;
let iRef= storageRef.child(path);
iRef.put(selectedFile).then((snapshot)=>{
item.image=selectedFile.name;
item.path=path;
return storageRef.child(item.path).getDownloadURL().then((url)=>{
//Setting Image Url below
this.imageUrl =url;
item.downloadUrl=this.imageUrl;
console.log(this.imageUrl);
return this.items.push(item);
});
}).catch((error)=>{
console.log(error);
});
}
但是您可以通过直接使用从storageRef.put() 的完成回调中获得的快照中的下载 URL 来大大简化代码:
for(let selectedFile of [(<HTMLInputElement>document.getElementById('image')).files[0]]){
let path=`/${this.folder}/${selectedFile.name}`;
let iRef= storageRef.child(path);
iRef.put(selectedFile).then((snapshot)=>{
item.image=selectedFile.name;
item.path=path;
var url = snapshot.downloadURL;
this.imageUrl =url;
item.downloadUrl=this.imageUrl;
return this.items.push(item);
});
}