我是使用Angular和Firebase Storage的新开发人员。我已经成功地将文档上传到Firebase存储中,但是我对如何获取下载URL并使之可用于其他组件感到困惑。
我尝试在finalize()之后使用then来添加它,但给了我一些新问题
import { Component, OnInit } from '@angular/core';
import {AngularFireUploadTask, AngularFireStorage} from '@angular/fire/storage';
import { AngularFirestore } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { tap, finalize } from 'rxjs/operators';
@Component({
selector: 'app-upload-page',
templateUrl: './upload-page.component.html',
styleUrls: ['./upload-page.component.css']
})
export class UploadPageComponent implements OnInit {
task: AngularFireUploadTask;
// Progress monitoring
percentage: Observable<number>;
snapshot: Observable<any>;
// Download URL
downloadURL: Observable<string>;
// State for dropzone CSS toggling
isHovering: boolean;
constructor(
private storage: AngularFireStorage,
private db: AngularFirestore
) {}
toggleHover(event: boolean) {
this.isHovering = event;
}
startUpload(event: FileList) {
// The File object
const file = event.item(0);
// The storage path
const path = `documents/${new Date().getTime()}_${file.name}`;
// metadata
const customMetadata = { app: 'LKMData in '+ file.type+ ' Format' };
// The main task
this.task = this.storage.upload(path, file, { customMetadata });
// Progress monitoring
this.percentage = this.task.percentageChanges();
this.snapshot = this.task.snapshotChanges().pipe(
tap(snap => {
if (snap.bytesTransferred === snap.totalBytes) {
// Update firestore on completion
this.db.collection('documents').add({ path, size: snap.totalBytes});
}
}),
finalize(() => this.downloadURL = this.storage.ref(path).getDownloadURL())
);
}
// Determines if the upload task is active
isActive(snapshot) {
return (
snapshot.state === 'running' &&
snapshot.bytesTransferred < snapshot.totalBytes
);
}
ngOnInit() {
}
}
我希望将下载URL发送到Firebase数据库并更新保存上传的文件的详细信息,或者有一种方法可以使存储中文件的所有URL可供组件使用
答案 0 :(得分:1)
StorageReference.getDownloadURL()
方法是异步的。通话完成后,下载URL才可用。
所以:
this.storage.ref(path).getDownloadURL().then((url) => {
this.downloadURL = url;
});
另请参阅: