如何使用 AngularFire 从 FireBase 存储中获取文件列表

How to get a list of files from FireBase Storage using AngularFire

我有一个 Angular 12 应用程序,它使用 Firebase 存储将一些文件存储在目录中。我使用 AngularFire 解决方案实现了与 Firebase 的集成。关于如何使用 AngularFire 存储功能的文档似乎没有包括如何列出目录中的所有文件。 Firebase 网站上有一些文档与此相关(listAll),但我似乎无法使用 AngularFire 使代码在 Angular 中工作。以下 Firebase 站点的代码示例...

import {
  getStorage,
  ref,
  listAll
} from "firebase/storage";

const storage = getStorage();

// Create a reference under which you want to list
const listRef = ref(storage, 'files/uid');

// Find all the prefixes and items.
listAll(listRef)
  .then((res) => {
    res.prefixes.forEach((folderRef) => {
      // All the prefixes under listRef.
      // You may call listAll() recursively on them.
    });
    res.items.forEach((itemRef) => {
      // All the items under listRef.
    });
  }).catch((error) => {
    // Uh-oh, an error occurred!
  });

我已经弄清楚(通过 AngularFire 文档)如何获取参考等(它与示例中的不同)但是当我到达'listAll'部分代码。

这是我在 Angular...

中能走多远

import {
  Component,
  OnInit
} from '@angular/core';
import {
  Observable
} from 'rxjs';
import {
  AngularFireStorage
} from '@angular/fire/compat/storage';

@Component({
  selector: 'app-openvideo',
  templateUrl: './openvideo.component.html',
  styleUrls: ['./openvideo.component.css'],
})
export class OpenvideoComponent implements OnInit {
  subscription;
  constructor(private storage: AngularFireStorage) {}

  async getVideoList() {
    const directory = 'samplevideos/';
    const listRef = this.storage.ref(directory);
    //Can't make the sample code work here
  }

  ngOnInit(): void {}

  ngOnDestroy() {}
}

理想的状态是我正在检索存储在目标目录中的文件列表,然后我可以对该列表做一些事情(即向用户显示列表,允许他们 select项目等。我觉得我在这里的挣扎是本机 Firebase 存储 API 和它的 AngularFire 实现上存在的文档之间的文档差距的组合,再加上对 promises、observables 的理解薄弱等等。作为旁注,我相信我已经完成了正确的配置(更改为 AppModule 等)以在我的组件中启用 firebase 解决方案并在其他组件中成功使用它(例如上传文件)所以我不认为问题是angularfire的核心配置之一。任何帮助将不胜感激。

经过反复试验,我想出了如何在 Angular 12 中完成这项工作。对于那些有兴趣在其 Firebase 存储库中获取文件列表然后填充数组的人,以便您可以在您的 Angular 组件中显示文件名和下载 link 我使用的代码在下面找到。我会第一个承认我不是世界上最伟大的编码员,所以使用风险自负!

//This is where you store the file names and download url's
filelist = []

//This is the function you call (put it in ngOnInit or something of the like) to get the filenames
getFileList() {
  const ref = this.storage.ref('');
  let myurlsubscription = ref.listAll().subscribe((data) => {
    for (let i = 0; i < data.items.length; i++) {
      let name = data.items[i].name;
      let newref = this.storage.ref(data.items[i].name);
      let url = newref.getDownloadURL().subscribe((data) => {
        this.filelist.push({
          name: name,
          videolink: data
        });
      });
    }
  });
}