【发布时间】:2019-09-06 00:00:33
【问题描述】:
我正在使用 angularfire2 将图像上传到 firebase 存储。上传工作得很好,尽管我在等待我的代码下载 url 可用的时间上遇到了麻烦。这是选择文件时的代码
async onFilesAdded(event){
console.log("file added")
if (event.target.files.length > 0) {
const file = event.target.files[0];
console.log("File name is:" + file.name)
await this.dataSvc.pushUpload(file).then(
(res) => {
console.log("download url is::" + this.dataSvc.downloadURL)
},
(err) => console.log("fail to upload file:" + err)
)
}
}
我的服务实现如下
pushUpload(file: File) {
const filePath = '/' + file.name;
const fileRef = this.storage.ref(filePath);
return new Promise<any>((resolve, reject) => {
const task = this.storage.upload(filePath, file);
task.snapshotChanges().pipe(
finalize(() => this.downloadURL = fileRef.getDownloadURL() )
).subscribe(
res => resolve(res),
err => reject(err))
}
)
}
我希望等到承诺得到解决并看到下载网址。但是我的代码似乎没有等待,我得到了未定义的 downloadUrl,几秒钟后,下载 url 实际显示在服务中。所以基本上我调用 pushUpload 的代码不会等待下载完成。
另一个我从来没有在 finalize 中获得下载 url 的变体
pushUpload(file: File) {
const path = '/' + file.name;
const ref = this.storage.ref(path);
let task = this.storage.upload(path, file);
let snapshot = task.snapshotChanges().pipe(
finalize( async() => {
this.downloadURL = await ref.getDownloadURL().toPromise();
console.log("download url i got is:" + this.downloadURL)
}),
);
}
【问题讨论】:
标签: angular firebase firebase-storage angularfire2