Angular 8 Firestore tutorial with CRUD application example - @angular/fire
Tags: angular8, firestore, crud, angularfire
Published: 2021-03-02 17:19:19

https://grokonez.com/frontend/angular/angular-8-firestore-tutorial-crud-examples-angularfire

Tutorial: Angular 8 Firestore tutorial with CRUD application example - @angular/fire

Cloud Firestore helps us store data in the cloud. It supports offline mode so our app will work fine (write, read, listen to, and query data) whether device has internet connection or not, it automatically fetches changes from our database to Firebase Server. We can structure data in our ways to improve querying and fetching capabilities. This tutorial shows you how to work with Firebase Firestore along with an Angular app that can do CRUD Operations.

Related Posts:
- <a href="https://grokonez.com/firebase/angular-8-firebase-tutorial-integrate-firebase-angular-8-app-angular-fire">Angular 8 Firebase tutorial: Integrate Firebase into Angular 8 App with @angular/fire</a>
- <a href="https://grokonez.com/frontend/angular/angular-8-firebase-tutorial-crud-operations-angular-fire-example">Angular 8 Firebase CRUD operations with @angular/fire</a>
- <a href="https://grokonez.com/frontend/upload-display-delete-files-angular-8-firebase-storage-angular-fire">Angular 8 – Upload/Display/Delete files to/from Firebase Storage using @angular/fire</a>

<!--more-->
<h2 id="technology-angular-8-firestore-crud">Technology - Angular 8 Firestore CRUD</h2>
- Angular 8
- @angular/fire 5.1.2
- firebase 5.10.1
<h2 id="set-up-firebase-projet-install-angular-fire">Set up the Firebase Project & Install @angular/fire</h2>
Please visit <a href="https://grokonez.com/firebase/angular-8-firebase-tutorial-integrate-firebase-angular-8-app-angular-fire">this post</a> to know step by step.

The only different for this tutorial is that, we use Firebase Firestore instead of Firebase Realtime Database:

<img src="https://grokonez.com/wp-content/uploads/2019/04/angular-8-firestore-turorial-create-database.png" alt="angular-8-firestore-turorial-create-database" width="657" height="416" class="alignnone size-full wp-image-17838" />
<h2 id="firebase-crud-operations-object">Firebase CRUD operations for Object</h2>
- Create an object binding/ Retrieve:

<pre><code class="language-java">item: AngularFirestoreDocument&lt;any&gt;;
// db: AngularFirestore
this.item = db.doc('item');

// or
Observable&lt;any&gt; item = db.doc('item').valueChanges();</code></pre>
- Create Operation:

<pre><code class="language-javascript">
// db: AngularFirestore
const itemRef = db.doc('item');

// set() for destructive updates
itemRef.set({ name: 'grokonez'});
</code></pre>

- Update operation:

<pre><code class="language-javascript">// db: AngularFirestore
const itemRef = db.doc('item');
itemRef.update({ url: 'grokonez.com'});</code></pre>

- Delete Operation:

<pre><code class="language-javascript">
// db: AngularFirestore
const itemRef = db.doc('item');
itemRef.delete();</code></pre>

<h2 id="firebase-crud-operaion-for-list-objects">Firebase CRUD operations for List of Objects</h2>
1. Create a list binding/ Retrieve:
- Returns an <code>Observable</code> of data as a synchronized array of JSON objects <strong>without</strong> snapshot metadata. It is simple to render to a view:
<pre><code class="language-javascript">items: Observable&lt;any[]&gt;;
// db: AngularFirestore
this.items = db.collection('items').valueChanges();</code></pre>

- Returns an <code>Observable</code> of data as a synchronized array of <code>DocumentChangeAction</code><>[] <strong>with</strong> metadata (the underlying data reference and snapshot <strong>id</strong>):

<pre><code class="language-javascript">items: Observable&lt;any[]&gt;;
// db: AngularFirestore
this.items = db.collection('items').snapshotChanges();</code></pre>

- Create Operation:

<pre><code class="language-javascript">
// db: AngularFirestore
const itemsRef = db.collection('items');
itemsRef.add({ site: 'grokonez.com' });
</code></pre>

- Update Operation:

<pre><code class="language-javascript">
// set(): destructive update
// delete everything currently in place, then save the new value
const itemsRef = db.collection('items'); // db: AngularFirestore
itemsRef.doc(key).set({ url: 'gkz.com' });

// update(): non-destructive update
// only updates the values specified
const itemsRef = db.collection('items'); // db: AngularFirestore
itemsRef.doc(key).update({ url: 'grokonez.com' });
</code></pre>

- Delete Operation:

<pre><code class="language-javascript">// db: AngularFirestore
const itemsRef = db.collection('items');
itemsRef.doc(key).delete();

// delete entire list
itemsRef.get().subscribe(
      querySnapshot =&gt; {
        querySnapshot.forEach((doc) =&gt; {
          doc.ref.delete();
        });
      },
      error =&gt; {
        console.log('Error: ', error);
      });</code></pre>
<h2 id="configure-offline-persistence">Configure offline persistence</h2>
By default, offline persistence is disabled. To enable it, call <code>enablePersistence()</code> method:

<pre><code class="language-javascript">firebase.firestore().enablePersistence()
  .catch(err =&gt; {
    if (err.code == 'failed-precondition') {
      // only be enabled in one tab at a a time (multiple tabs open)
    } else if (err.code == 'unimplemented') {
      // browser does not support all of the features required to enable persistence
    }
  });</code></pre>
<h2>Project Goal - Angular 8 Firestore CRUD</h2>
We will build an Angular 8 Firebase App using <code>@angular/fire</code> that can:
- add/remove Customer
- show all Customers
- update Customer's status
to Firebase Firestore.

<img src="https://grokonez.com/wp-content/uploads/2019/04/angular-8-firestore-turorial-demo-goal.png" alt="angular-8-firestore-turorial-demo-goal" width="700" height="479" class="alignnone size-full wp-image-17832" />
<h2 id="project-structure">Project Structure</h2>
<img src="https://grokonez.com/wp-content/uploads/2019/04/angular-8-firestore-turorial-project-structure.png" alt="angular-8-firestore-turorial-project-structure" width="237" height="530" class="alignnone size-full wp-image-17834" />

- <strong>environment.ts</strong> configure information to connect with Firebase Project.
- <strong>customer.ts</strong> defines <code>Customer</code> class data model.
- <strong>customer.service.ts</strong> defines <code>CustomerService</code> that uses <code>@angular.fire</code> to interact with Firebase.
- 3 Angular components:
+ <code>create-customer</code> for creating new item.
+ <code>customer-details</code> shows item detais
+ <code>customers-list</code> contains list of items, this is parent component of <code>customer-details</code>
- <code>app-routing.module.ts</code> defines how we route Angular components.
- <code>app.module.ts</code> declares and imports necessary environment & modules.
<h2 id="set-up-firease-project-install-angular-fire">Set up the Firebase Project & Install @angular/fire</h2>
Please visit <a href="https://grokonez.com/firebase/angular-8-firebase-tutorial-integrate-firebase-angular-8-app-angular-fire">this post</a> to know step by step.

<img src="https://grokonez.com/wp-content/uploads/2019/04/angular-8-firestore-turorial-create-database.png" alt="angular-8-firestore-turorial-create-database" width="657" height="416" class="alignnone size-full wp-image-17838" />
<h2 id="add-firebase-config-to-enviroments-variable">Add Firebase config to environments variable</h2>
Open <strong>/src/environments/environment.ts</strong>, add your Firebase configuration that we have saved when Popup window was shown:
<pre><code class="language-javascript">export const environment = {
  ...
  firebase: {
    apiKey: 'xxx',
    authDomain: 'gkz-angular-firebase.firebaseapp.com',
    databaseURL: 'https://gkz-angular-firebase.firebaseio.com',
    projectId: 'gkz-angular-firebase',
    storageBucket: 'gkz-angular-firebase.appspot.com',
    messagingSenderId: '123'
  }
};</code></pre>
<img src="https://grokonez.com/wp-content/uploads/2019/04/angular-8-firebase-tutorial-integrate-angular-fire-popup.png" alt="angular-8-firebase-tutorial-integrate-angular-fire-popup" width="663" height="403" class="alignnone size-full wp-image-17756" />
<h2 id="create-services-components">Create Service & Components</h2>
Run the commands below:
- <code>ng g s customers/Customer</code>
- <code>ng g c customers/CustomerDetails</code>
- <code>ng g c customers/CustomersList</code>
- <code>ng g c customers/CreateCustomer</code>
<h2 id="setup-ngmodle">Setup @NgModule</h2>
<em>app.module.ts</em>

<pre><code class="language-javascript">import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { FormsModule } from '@angular/forms';

import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule, FirestoreSettingsToken } from '@angular/fire/firestore';
import { environment } from '../environments/environment';

import { AppComponent } from './app.component';
import { CustomerDetailsComponent } from './customers/customer-details/customer-details.component';
import { CustomersListComponent } from './customers/customers-list/customers-list.component';
import { CreateCustomerComponent } from './customers/create-customer/create-customer.component';

@NgModule({
  declarations: [
    AppComponent,
    CustomerDetailsComponent,
    CustomersListComponent,
    CreateCustomerComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFirestoreModule
  ],
  providers: [{ provide: FirestoreSettingsToken, useValue: {} }],
  bootstrap: [AppComponent]
})
export class AppModule { }</code></pre>
<h2 id="create-model-class">Create Model Class</h2>
<em>customer.ts</em>

<pre><code class="language-javascript">
export class Customer {
  key: string;
  name: string;
  age: number;
  active = true;
}</code></pre>

The <code>key</code> field is important for updating item.

More at: https://grokonez.com/frontend/angular/angular-8-firestore-tutorial-crud-examples-angularfire