同时删除Cloud Firestore文档和Fire Storage文件

时间:2020-08-22 23:28:15

标签: javascript angular firebase google-cloud-firestore firebase-storage

我有一个Cloud Firestore文档集合(有关我上传的文件的元数据),并且在Firebase Storage中有这些文件的存储桶。

我想使用我的Angular应用程序删除给定的文件。我可以删除Firestore文档,但是无法删除存储中的相应文件。

编译错误: Property 'then' does not exist on type 'Observable<any>'.

import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs';                      // I was experimenting with onPromise()
import { finalize, tap } from 'rxjs/operators';
import { AngularFireStorage } from '@angular/fire/storage';
import { StateService } from '../services/state.service';

// ...

export class AdminComponent implements OnInit {

    isProgressVisible: boolean;

    constructor(private storage: AngularFireStorage, public stateService: StateService) {
        this.isProgressVisible = false;
    }

    // ...    

    deleteFile(file): void {
        this.isProgressVisible = true;

        let storagePath = file.storagePath;                     // ex: 'uploads/1598066351161_myfile.txt'
        let delimiter = storagePath.indexOf('/');
        let docID = file.storagePath.substring(delimiter + 1);  // ex: '1598066351161_myfile.txt'

        let self = this;
 
        this.stateService.firebase.firestore().collection('files').doc(docID).delete().then(function () {
            console.log('cloud firestore doc deleted');

            let ref = self.storage.ref(storagePath);            // delete the file from Storage
            ref.delete().then(function () {
                console.log('file deleted from storage!');
            }).catch(function (error) {
                console.error('Error deleting file from storage:', error);
            });

        }).catch(function (error) {
            console.error('Error deleting cloud firestore doc:', error);
        });
    }
}

感谢您的帮助!

1 个答案:

答案 0 :(得分:0)

this.stateService.firebase.firestore().collection('files').doc(docID).delete()返回一个不可观察的观察值。您应该使用toPromise()将其转换为promise,或者使用subscribe而不是then

检查this post以获得更多见解。