我正在尝试检索存储在Firebase存储中的每个图像的下载网址。该网址保存在Firebase Firestore中。以下代码映射从Firebase Firestore从snapshotChanges方法接收的文档。对于每个文档,我都会获得下载URL。但是这个方法返回一个promise对象。因此,map方法在返回promise对象之前完成,这会导致data.downloadUrl为空。
this.listingCollection = this.db.collection<Listing>('listings');
this.listings = this.listingCollection.snapshotChanges().map(actions => {
return actions.map(a => {
const data = a.payload.doc.data() as Listing;
const id = a.payload.doc.id;
if (data.path) {
let storageRef = firebase.storage().ref();
let spaceRef = storageRef.child(data.path);
spaceRef.getDownloadURL().then((url) => {
data.downloadUrl = url;
console.log(url);
}).catch((error) => {
});
}
return { id, ...data };
});
});
我正在HTML页面中使用downloadUrl。
<ng-container matColumnDef="downloadUrl">
<mat-header-cell *matHeaderCellDef></mat-header-cell>
<mat-cell *matCellDef="let element">{{element.downloadUrl}}</mat-cell>
</ng-container>
请帮忙。感谢。
答案 0 :(得分:0)
发现将图像上传到Firebase存储时,downloadUrl可用:
addListing(listing) {
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) => {
listing.image = selectedFile.name;
listing.path = snapshot.downloadURL;
return this.listingCollection.add(listing);
})
}
}
答案 1 :(得分:0)
尝试此代码
this.listingCollection = this.db.collection < Listing > ('listings');
this.listings = this.listingCollection.snapshotChanges()
.map(actions => {
return actions.map(async a => {
const data = a.payload.doc.data() as Listing;
const id = a.payload.doc.id;
if (data.path) {
let storageRef = firebase.storage().ref();
let spaceRef = storageRef.child(data.path);
const url = await spaceRef.getDownloadURL();
data.downloadUrl = url;
console.log(url);
}
return {
id,
...data
};
});
});
值得一提的是,有一个官方的firebase库,用于angular @ angular / fire,您应该使用它代替正常的软件包