Angular Firebase Tutorial: Read/Write data into a NoSql Database Collection

Chris House
SlackerNoon
Published in
2 min readNov 8, 2017

Firebase Cloud Firestore, which is currently in beta stage, is “the next generation of the Realtime Database with more powerful queries and automatic scaling.” It is was acquired by Google in 2014, and is a realtime cloud-based NoSql database solution.

Step 1: Set up your environment.

To set up your Firebase environment, please see my previous article.

Step 2: Set up new collection in Firebase’s Cloud Firestore.

Step 3: Modify typescript code.

In your component, we want to add a new tshirt interface.

export interface Shirt { name: string; price: number; }

Next we will inject the AngularFireAuth and AngularFireStore to the constructor, and subscribe to the tshirts collection.

Here is how your component should look so far:

export class AppComponent {_db:AngularFirestore;
shirts: Observable<any[]>;
constructor(public afAuth: AngularFireAuth, db: AngularFirestore) {
this.afAuth.auth.signInAnonymously();
this.shirts = db.collection('tshirts').valueChanges();
this._db = db;
}
}

Step 4: Create a simple form in your html.

We want two textboxes, a submit button, and a way to display the realtime database collection.

<div style="text-align:center">
<br> Name:
<input #shirtName>
<br> Price:
<input #price>
<br>
<button (click)="addTshirt(shirtName.value, price.value)">Add some shirts</button>
<br>
<div style="text-align:center;display:unset;">
List of Shirts:
<ul>
<li *ngFor="let shirt of shirts | async">
{{ shirt.name }} is ${{ shirt.price }}
</li>
</ul>
</div>
</div>

Step 5: Write a function called addTshirt() in your typescript.

addTshirt(sName: string, dPrice: number){
let shirtsCollection = this._db.collection<Shirt>('tshirts');
shirtsCollection.add({ name: sName, price: dPrice });
}

Finally: Run the app.

To run in development mode, open a terminal and run:

ng serve — open

To build for production with AOT and treeshaking:

ng build --prod --build-optimizer

Here is the git repo.

Demo is coming soon. Still debating the best way to structure/host the demos.

example screenshot

--

--