DEV Community

loizenai
loizenai

Posted on

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

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:

Technology - Angular 8 Firestore CRUD

  • Angular 8
  • @angular/fire 5.1.2
  • firebase 5.10.1

    Set up the Firebase Project & Install @angular/fire

    Please visit this post to know step by step.

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

angular-8-firestore-turorial-create-database

Firebase CRUD operations for Object

  • Create an object binding/ Retrieve:
item: AngularFirestoreDocument<any>;
// db: AngularFirestore
this.item = db.doc('item');

// or
Observable<any> item = db.doc('item').valueChanges();
  • Create Operation:

// db: AngularFirestore
const itemRef = db.doc('item');

// set() for destructive updates
itemRef.set({ name: 'grokonez'});
  • Update operation:
// db: AngularFirestore
const itemRef = db.doc('item');
itemRef.update({ url: 'grokonez.com'});
  • Delete Operation:

// db: AngularFirestore
const itemRef = db.doc('item');
itemRef.delete();

Firebase CRUD operations for List of Objects

  1. Create a list binding/ Retrieve:
  2. Returns an Observable of data as a synchronized array of JSON objects without snapshot metadata. It is simple to render to a view:
    items: Observable<any[]>;
    // db: AngularFirestore
    this.items = db.collection('items').valueChanges();
  • Returns an Observable of data as a synchronized array of DocumentChangeAction<>[] with metadata (the underlying data reference and snapshot id):
items: Observable<any[]>;
// db: AngularFirestore
this.items = db.collection('items').snapshotChanges();
  • Create Operation:

// db: AngularFirestore
const itemsRef = db.collection('items');
itemsRef.add({ site: 'grokonez.com' });
  • Update Operation:

// 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' });
  • Delete Operation:
// db: AngularFirestore
const itemsRef = db.collection('items');
itemsRef.doc(key).delete();

// delete entire list
itemsRef.get().subscribe(
      querySnapshot => {
        querySnapshot.forEach((doc) => {
          doc.ref.delete();
        });
      },
      error => {
        console.log('Error: ', error);
      });

Configure offline persistence

By default, offline persistence is disabled. To enable it, call enablePersistence() method:

firebase.firestore().enablePersistence()
  .catch(err => {
    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
    }
  });

Project Goal - Angular 8 Firestore CRUD

We will build an Angular 8 Firebase App using @angular/fire that can:

  • add/remove Customer
  • show all Customers
  • update Customer's status to Firebase Firestore.

angular-8-firestore-turorial-demo-goal

Project Structure

angular-8-firestore-turorial-project-structure

  • environment.ts configure information to connect with Firebase Project.
  • customer.ts defines Customer class data model.
  • customer.service.ts defines CustomerService that uses @angular.fire to interact with Firebase.
  • 3 Angular components:
  • create-customer for creating new item.
  • customer-details shows item detais
  • customers-list contains list of items, this is parent component of customer-details
  • app-routing.module.ts defines how we route Angular components.
  • app.module.ts declares and imports necessary environment & modules.

    Set up the Firebase Project & Install @angular/fire

    Please visit this post to know step by step.

angular-8-firestore-turorial-create-database

Add Firebase config to environments variable

Open /src/environments/environment.ts, add your Firebase configuration that we have saved when Popup window was shown:

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'
  }
};

angular-8-firebase-tutorial-integrate-angular-fire-popup

Create Service & Components

Run the commands below:

  • ng g s customers/Customer
  • ng g c customers/CustomerDetails
  • ng g c customers/CustomersList
  • ng g c customers/CreateCustomer

    Setup @NgModule

    app.module.ts
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 { }

Create Model Class

customer.ts


export class Customer {
  key: string;
  name: string;
  age: number;
  active = true;
}

The key field is important for updating item.

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

Top comments (0)