获取下载 URL 并使其可供其他组件使用

Getting Download URL and Make it Available to other components

我是使用 Angular 和 Firebase 存储的新开发者。我已成功将文档上传到 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 数据库并更新包含已上传文件的详细信息,或者有办法使存储中的所有 URLS 文件可用用于组件

StorageReference.getDownloadURL() 方法是异步的。只有在通话完成后才能下载 URL。

所以:

this.storage.ref(path).getDownloadURL().then((url) => {
  this.downloadURL = url;
});

另见:

  • (以及从那里链接的那些)