You have unlimited access as a PRO member
You are receiving a free preview of 3 lessons
Your free preview as expired - please upgrade to PRO
Contents
Recent Posts
- Object Oriented Programming With TypeScript
- Angular Elements Advanced Techniques
- TypeScript - the Basics
- The Real State of JavaScript 2018
- Cloud Scheduler for Firebase Functions
- Testing Firestore Security Rules With the Emulator
- How to Use Git and Github
- Infinite Virtual Scroll With the Angular CDK
- Build a Group Chat With Firestore
- Async Await Pro Tips
Delete Firestore Collections With Angular and RxJS
Episode 80 written by Jeff DelaneyFirebase provides official guidance to delete collections, but it’s not exactly the ideal reactive way to handle things in Angular. In this lesson, I will teach you how to create a an Observable that recursively removes Firestore documents in batches.
In order to follow this lesson you will need AngularFire installed in your project. We will also be using lettable operators introduced in RxJS v5.5.
Deleting Firestore Collections in Angular
First, let’s generate our own Angular service to extend AngularFirestore.
ng g service firestore |
Next, let’s flesh out the service by importing the necessary RxJS operators and inject Firestore in the constructor.
import { Injectable } from '@angular/core'; |
Generating Dummy Data for Firestore
For the purposes of this demo, I am using FakerJS to quickly add documents to Firestore. This part is completely optional, but it’s a convenient tool for generating seed data in Firebase.
npm install faker --save |
Now we just need a method that will generate the data in a loop and add each document to Firestore.
|
Recursive Observable to Delete Firestore Collections
You may not be familiar with the expand operator, but it happens to be perfect for this situation. Each delete operation is a batched transaction, which Firebase returns as a promise. For each operation, we query a batch of documents and wait for the delete promise to resolve. This function is called recursively (using expand) until the snapshot.length === 0
, at which point takeWhile
will trigger the complete signal from the Observable.
deleteCollection(path: string, batchSize: number): Observable<any> { |
deleteCollection(path: string, batchSize: number): Observable<any> { |
As an added bonus, our RxJS/AngularFire method requires fewer lines of code then the official docs and can be canceled at any time using unsubscribe
.
The End
You now have an reactive helper for deleting Firestore documents in batches. Let me know if you have an feedback in the comments or on Slack.