Angular 6 Firebase CRUD operations with AngularFire2 v5

In this tutorial, we’re gonna create a simple Angular 6 App that does CRUD to create, read, update, delete data to/from Firebase Realtime Database using AngularFire2.

Related Posts:
How to integrate Firebase with Angular 6 – AngularFire2 V5
Angular 6 Firebase – Upload/Display/Delete Files from Storage

I. Technology

– Angular 6
– AngularFire2 5.0

II. How to do

1. Set up the Firebase Project & Install AngularFire2

Please visit this post to know step by step.

2. Object
2.1 Create an object binding/ Retrieve
item: FirebaseObjectObservable;
// db: AngularFireDatabase
this.item = db.object('item').valueChanges();
2.2 Create
// db: AngularFireDatabase
const itemRef = db.object('item');

// set() for destructive updates
itemRef.set({ name: 'javasampleapproach'});
2.3 Update
// db: AngularFireDatabase
const itemRef = db.object('item');
itemRef.update({ url: 'grokonez.com'});
2.4 Delete
// db: AngularFireDatabase
const itemRef = db.object('item');
itemRef.remove();
3. List of Objects
3.1 Create a list binding/ Retrieve

– 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;
// db: AngularFireDatabase
this.items = db.list('items').valueChanges();

– Returns an Observable of data as a synchronized array of AngularFireAction<DatabaseSnapshot>[] with metadata (the underyling DatabaseReference and snapshot key):

items: Observable;
// db: AngularFireDatabase
this.items = db.list('items').snapshotChanges();
3.2 Create
// db: AngularFireDatabase
const itemsRef = db.list('items');
itemsRef.push({ site: 'grokonez.com' });
3.3 Update
// set(): destructive update
// delete everything currently in place, then save the new value
const itemsRef = db.list('items'); // db: AngularFireDatabase
itemsRef.set('key', { url: 'jsa.com' });

// update(): non-destructive update
// only updates the values specified
const itemsRef = db.list('items'); // db: AngularFireDatabase
itemsRef.update('key', { url: 'javasampleapp.com' });
3.4 Delete
// db: AngularFireDatabase
const itemsRef = db.list('items');
itemsRef.remove('key');

// delete entire list
itemsRef.remove();

III. Practice

1. Project Overview
1.1 Goal

We will build an Angular 6 Firebase App using AngularFire2 that can:
– add/remove Customer
– show all Customers
– update Customer’s status

angular-6-firebase-crud-realtime-database-goal

1.2 Structure

angular-6-firebase-crud-realtime-database-project-structure

2. Step by step
2.1 Set up the Firebase Project & Install AngularFire2

Please visit this post to know step by step.

2.2 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 = {
  production: false,
  firebase: {
    apiKey: 'xxx',
    authDomain: 'jsa-angular6.firebaseapp.com',
    databaseURL: 'https://jsa-angular6.firebaseio.com',
    projectId: 'jsa-angular6',
    storageBucket: '',
    messagingSenderId: 'xxx'
  }
};
2.3 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

2.4 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 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';

import { environment } from '../environments/environment';
import { AppComponent } from './app.component';

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

@NgModule({
  declarations: [
    AppComponent,
    CustomersListComponent,
    CustomerDetailsComponent,
    CreateCustomerComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    AppRoutingModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule, // for database
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
2.5 Model Class

customer.ts

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

customer.service.ts

import { Injectable } from '@angular/core';
import { AngularFireDatabase, AngularFireList } from 'angularfire2/database';
import { Customer } from './customer';

@Injectable({
  providedIn: 'root'
})
export class CustomerService {

  private dbPath = '/customers';

  customersRef: AngularFireList = null;

  constructor(private db: AngularFireDatabase) {
    this.customersRef = db.list(this.dbPath);
  }

  createCustomer(customer: Customer): void {
    this.customersRef.push(customer);
  }

  updateCustomer(key: string, value: any): void {
    this.customersRef.update(key, value).catch(error => this.handleError(error));
  }

  deleteCustomer(key: string): void {
    this.customersRef.remove(key).catch(error => this.handleError(error));
  }

  getCustomersList(): AngularFireList {
    return this.customersRef;
  }

  deleteAll(): void {
    this.customersRef.remove().catch(error => this.handleError(error));
  }

  private handleError(error) {
    console.log(error);
  }
}
2.7 Customer Details Compoment

customer-details.component.ts

import { Component, OnInit, Input } from '@angular/core';

import { Customer } from '../customer';
import { CustomerService } from '../customer.service';

@Component({
  selector: 'customer-details',
  templateUrl: './customer-details.component.html',
  styleUrls: ['./customer-details.component.css']
})
export class CustomerDetailsComponent implements OnInit {

  @Input() customer: Customer;

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
  }

  updateActive(isActive: boolean) {
    this.customerService.updateCustomer(this.customer.key, { active: isActive });
  }

  deleteCustomer() {
    this.customerService.deleteCustomer(this.customer.key);
  }
}

customer-details.component.html

{{customer.name}}
{{customer.age}}
{{customer.active}}
Inactive Active Delete
2.8 Customers List Component

customers-list.component.ts

import { Component, OnInit } from '@angular/core';
import { map } from 'rxjs/operators';

import { CustomerService } from '../customer.service';

@Component({
  selector: 'customers-list',
  templateUrl: './customers-list.component.html',
  styleUrls: ['./customers-list.component.css']
})
export class CustomersListComponent implements OnInit {

  customers: any;

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
    this.getCustomersList();
  }

  getCustomersList() {
    // Use snapshotChanges().map() to store the key
    this.customerService.getCustomersList().snapshotChanges().pipe(
      map(changes =>
        changes.map(c => ({ key: c.payload.key, ...c.payload.val() }))
      )
    ).subscribe(customers => {
      this.customers = customers;
    });
  }

  deleteCustomers() {
    this.customerService.deleteAll();
  }

}

customers-list.component.html:

Customers

2.9 Create Customer Component

create-customer.component.ts

import { Component, OnInit } from '@angular/core';
import { FormsModule } from '@angular/forms';

import { Customer } from '../customer';
import { CustomerService } from '../customer.service';

@Component({
  selector: 'create-customer',
  templateUrl: './create-customer.component.html',
  styleUrls: ['./create-customer.component.css']
})
export class CreateCustomerComponent implements OnInit {

  customer: Customer = new Customer();
  submitted = false;

  constructor(private customerService: CustomerService) { }

  ngOnInit() {
  }

  newCustomer(): void {
    this.submitted = false;
    this.customer = new Customer();
  }

  save() {
    this.customerService.createCustomer(this.customer);
    this.customer = new Customer();
  }

  onSubmit() {
    this.submitted = true;
    this.save();
  }
}

create-customer.component.html:

Create Customer

You submitted successfully!

2.10 Routing Module

app-routing.module.ts

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

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';

const routes: Routes = [
    { path: '', redirectTo: 'customers', pathMatch: 'full' },
    { path: 'customers', component: CustomersListComponent },
    { path: 'add', component: CreateCustomerComponent }
];

@NgModule({
    imports: [RouterModule.forRoot(routes)],
    exports: [RouterModule]
})
export class AppRoutingModule { }

app.component.html:

{{title}}

{{description}}

To understand how to use Angular Routing Module, please visit:
How to work with Angular Routing – Spring Boot + Angular 4

3. Check Result

– Open browser with url http://localhost:4200/.

– Add Customer:

angular-6-firebase-crud-realtime-database-result-add-customer

– View Customers and change Active Status:

angular-6-firebase-crud-realtime-database-result-update-customer

>> Firebase Console:

angular-6-firebase-crud-realtime-database-firebase-console-result

– Delete a Customer:

– Delete all Customers:

angular-6-firebase-crud-realtime-database-result-delete-all-customer

>> Firebase Console is clean now.

III. Source Code

Angular6FirebaseCRUD



By grokonez | June 18, 2018.


Related Posts


4 thoughts on “Angular 6 Firebase CRUD operations with AngularFire2 v5”

  1. How search a particular register on AngularFireDatabase? I’m stuck on how to get a record and how to look for it by a certain attribute.

Got Something To Say:

Your email address will not be published. Required fields are marked *

*