0

我能够获取存储中的项目的URL,但我无法将它们保存到数据库。 item.downloadUrl无法收到this.imageUrl。有没有其他方法可以将一个项目的downloadUrl保存到数据库中?我想使用angularfire2将图像的下载保存到数据库中

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); 
     }); 
    } 
    } 

回答

0

当下载URL尚未被检索到时,您正在将项目推送到数据库。为了解决这个问题,将调用databaseRef.push()入则:

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); 
    }); 
} 

但是你可以直接使用下载URL从您在完成回调从storageRef.put()获取快照大大简化代码:

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); 
    }); 
} 
相关问题