Building a Firebase CRUD Service for Angular

Colum Ferry
4 min readDec 21, 2019

Anyone who knows me, knows I 😍😍 Firebase. It could be considered unhealthy πŸ˜‚. Despite my love for it, I have had my fair share of disagreements with it. The biggest one that comes to mind relates to Firestore.

NOTE: This article assumes you have a basic knowledge of how Firestore works. (docs)

This article will contain:

  • πŸ€” The Problem β€” Something that annoyed me
  • πŸ’ͺ My Solution β€” A brief overview
  • 🀩 LET’S BUILD! β€” Party time! πŸŽ‰πŸŽ‰

πŸ€” The Problem

I tend to use Firestore as my go to NoSQL store. But when we pair it with AngularFire the examples shown are at times not perfect, especially when we try to adhere to the DRY Principle.

The examples all tend to start with your call to the collection method in your Component to ensure you are working with the correct collection in Firestore. But all these calls to collection add up. There must be a better way?

πŸ’ͺ My Solution

To me, there is! But, this is subjective. I create a Generic Firebase CRUD Service*, that accepts a Type to define the model that I want to store in my Collection on Firestore.

This is what we are going to build in this article!

* I call this a service, but it is unlike a standard Angular Service that can be injected into a constructor, rather it is simply an instantiated class.

🀩 LET’S BUILD!

Ok, before we begin, let me take a moment to state that when I do this in codebases I work on, I tend to use the Bridge Pattern, by setting up a base Implementation for the CRUD Service, then define a Concrete Implementation of this, specific to Firetore.
My Abstractions have reference to the base Implementation but use the Firestore Concrete Implementation.

If any of this seems confusing, I highly recommend you read the Bridge Pattern article linked!

We’ll break this build down into a few steps:

  • Setup β€” Setting up the class!
  • Create β€” The code to add the Document (henceforth called the Entity)

--

--

Colum Ferry

Software Engineer @nrwl . Co-Founder of GrammarGuru. JavaScript Enthusiast. Married with 2 amazing kids. Powered by Coffee. Opinions my own.