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); 
    }); 
} 
相關問題