Angular中通过AngularFire获取Firebase Storage目录文件列表
解决方案
你不需要额外导入原生Firebase的listAll方法,@angular/fire/compat/storage返回的AngularFireStorageReference对象已经封装了该方法,直接调用即可。
async/await 实现版本
适配你现有标记了async的方法,直接使用await调用即可:
import { Component, OnInit } from '@angular/core'; import { AngularFireStorage } from '@angular/fire/compat/storage'; @Component({ selector: 'app-openvideo', templateUrl: './openvideo.component.html', styleUrls: ['./openvideo.component.css'], }) export class OpenvideoComponent implements OnInit { // 存储最终可渲染的视频列表 videoList: {name: string, path: string, downloadUrl: string}[] = []; subscription; constructor(private storage: AngularFireStorage) {} async getVideoList() { const directory = 'samplevideos/'; const listRef = this.storage.ref(directory); try { const listResult = await listRef.listAll(); // 遍历所有文件 for (const itemRef of listResult.items) { this.videoList.push({ name: itemRef.name, // 文件名称 path: itemRef.fullPath, // 文件完整存储路径 downloadUrl: await itemRef.getDownloadURL() // 文件访问地址 }); } // 此处this.videoList可直接用于前端模板渲染 console.log('获取到的视频列表:', this.videoList); } catch (error) { console.error('获取视频列表失败:', error); } } ngOnInit(): void { // 页面加载时调用方法获取列表 this.getVideoList(); } ngOnDestroy() { if (this.subscription) { this.subscription.unsubscribe(); } } }
Observable 实现版本
如果需要结合RxJS的操作符做链式处理,可以使用以下写法:
import { Component, OnInit } from '@angular/core'; import { from, Subscription } from 'rxjs'; import { switchMap } from 'rxjs/operators'; import { AngularFireStorage } from '@angular/fire/compat/storage'; @Component({ selector: 'app-openvideo', templateUrl: './openvideo.component.html', styleUrls: ['./openvideo.component.css'], }) export class OpenvideoComponent implements OnInit { videoList: {name: string, path: string, downloadUrl: string}[] = []; subscription: Subscription; constructor(private storage: AngularFireStorage) {} getVideoList() { const directory = 'samplevideos/'; const listRef = this.storage.ref(directory); return from(listRef.listAll()).pipe( switchMap(async listResult => { const list = []; for (const itemRef of listResult.items) { list.push({ name: itemRef.name, path: itemRef.fullPath, downloadUrl: await itemRef.getDownloadURL() }); } return list; }) ); } ngOnInit(): void { this.subscription = this.getVideoList().subscribe({ next: (list) => { this.videoList = list; }, error: (err) => { console.error('获取视频列表失败', err); } }) } ngOnDestroy() { this.subscription?.unsubscribe(); } }
注意事项
- 确保Firebase Storage的安全规则已经开放了对应目录的
list权限,测试阶段可以临时使用如下规则(生产环境请替换为符合业务要求的权限控制逻辑):
rules_version = '2'; service firebase.storage { match /b/{bucket}/o { match /samplevideos/{allPaths=**} { allow read, list: if true; } } }
- 如果你需要遍历子目录下的文件,可以对
listResult.prefixes返回的每个文件夹引用递归调用listAll方法即可。
内容的提问来源于stack exchange,提问作者Artemis J
相关产品推荐
相关产品推荐

