How to integrate firebase in angular

Angular firebase integration – Today we will learn firebase integration in Angular 8. We’ll learn, How to add, retrieve and delete record in firebase. Firebase is a Backend-as-a-Service — BaaS — that started as a YC11 startup and grew up into a next-generation app-development platform on Google Cloud Platform. Firebase frees developers to focus crafting fantastic user experiences. You don’t need to manage servers. You don’t need to write APIs. Firebase is your server, your API and your datastore, all written so generically that you can modify it to suit most needs. Yeah, you’ll occasionally need to use other bits of the Google Cloud for your advanced applications. firebase integration in angular is very easy. So let’s get started with the Angular firebase integration.

When we’re finished, it will look like this:

Let’s get started

Create Angular 8 Application

Before start Firebase integration in Angular 8. We need a Angular 8 Project. If you don’t know how to create a new angular 8 project. Follow this tutorial.

Install the Firebase Module

To make any type of interaction with the Firebase server you need firebase module. To install it type the below command and hit enter, will install the firebase module

npm i firebase

Creating Firebase Database

Now that our app is set up, we’ll need to create an account and database on Firebase so that we can link up our application to it.

Open the firebase website and click Get Started

Now the firebase will asked you to authenticate with your Google account. Select the account that you’d like this project to be affiliated with, and press OK

This should take you to the Firebase console, which looks something like this:

Click on the Create a project will open a dialog to create new project. like this

Enter the project name and accept the terms and conditions and hit Create Project button, It will create new project.

Now go to the project dashboard page. The dashboard page will looks like this

Here you will see the three option. Since we’ll be building a web app, Select third option`. This will open a popup to create web app that looks like this:

Enter the web app name and click on Register app button, will create web app and will show the some code that looks like this

Since we’ll be importing Firebase into our project using ES6 modules, we won’t need those script tags. That config object is important though: it’s how we authenticate our Angular 8 application with our Firebase database. So copy the firebaseConfig object and add this object in the environment.ts file

export const environment = {
  production: false,
  firebase: {
    apiKey: "AIzaSyAluQF1dceN0z-ibQrqSlduEfexUA7DrXw",
    authDomain: "w3path-5b087.firebaseapp.com",
    databaseURL: "https://w3path-5b087.firebaseio.com",
    projectId: "w3path-5b087",
    storageBucket: "",
    messagingSenderId: "1063357243120",
    appId: "1:1063357243120:web:2744a797b0ff6e9f"
  }
};

Configure Firebase in Angular 8 application

We will create Service and initialize firebase app so that we can use firebase everywhere in our application. To do so, run the below command

ng g service services\firebase

This command will create a new service named FirebaseService.

Next, We will import the firebase and initialize the app. After the changes our FirebaseService will looks like this

import { Injectable } from '@angular/core';
import * as firebase from 'firebase';
import { environment } from '../../environments/environment';

firebase.initializeApp(environment.firebase);

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

  constructor() { }


  db(table) {
    return firebase.database().ref(table);
  }
  create(table, data) {
    this.db(table).push(data);
  }
  remove(segment) {
    return firebase.database().ref(segment).remove();
  }

}

Create Database

After the setup firebase class in Angular 8 application, click on the Continue to console button will redirect you to the dashboard. Here you will find Database option in the left sidebar. To create database click on Database menu. Database page will looks like this

Click on the Create Database button, will open dialog box. Click on the next will ask for the Cloud Firestore location choose location and hit Done button will create database for you.

One last thing we’ll need to do before we can dive into roughing out our App. We need to temporarily disable authentication requirements on our app so that we can add and remove items without needing to have any kind of user authentication flow.

Choose the Realtime Database, you’ll see a Rules tab. This will cause an object to appear that looks something like this:

{
  /* Visit https://firebase.google.com/docs/database/security to learn more about security rules. */
  "rules": {
    ".read": false,
    ".write": false
  }
}

We need to set .read and .write to both be equal to true, otherwise later, when we try to add data to our database from our application, Firebase won’t let us.

Add HTML markup

Open your component.ts file and put the below html . I am going to add in app.component.ts file

<div class="container mt-5">
    <div class="row">
        <div class="col-md-6">
            <h2 class="text-left">Firebase Demo</h2>
        </div>
        <div class="col-md-6 text-right"> 
          <input type="text" placeholder="Title" [(ngModel)]="title" #ctrl="ngModel" />
          <button (click)="create()">Add Item</button>            
        </div>
    </div>
    <table class="table table-bordered mt-3">
      <thead>
        <tr>
          <th>ID</th>
          <th>Title</th>
          <th>Action</th>
        </tr>
      </thead>
      <tbody>
          <tr *ngIf="processing"><td class="text-center" colspan="3">Loading...</td></tr>
          <tr *ngIf="!processing &amp;&amp; todos.length < 1"><td class="text-center" colspan="3">No record found</td></tr>
          <tr *ngFor="let item of todos; let i = index;">
              <td width="20">{{i+1}}</td>
              <td>{{item.title}}</td>
              <td width="100">                
                  <button type="button" class="btn btn-danger mr-1" (click)="delete(item.id)">Delete</button>
              </td>
            </tr>
      </tbody>
    </table>
  </div>

Import FirebaseService

Next, We will import the FirebaseService in the app.component.ts file

import { FirebaseService } from 'src/app/services/firebase.service';

Add Item in the database

Add the below method in your app.component.ts file. This method will be able to add the data to the firebase database

create() {
    const item = {
        title: this.title
    }
    this.title = '';
    const itemsRef = this.firebaseService.create('items', item);
}

Retrieving Items from the database

This method will retrieve the list from the database

getList() {
  const itemsRef = this.firebaseService.db('items');
  itemsRef.limitToLast(10).on('value', (snapshot) => {
      let items = snapshot.val();
      let newState = [];
      for (let item in items) {
          newState.unshift({
              id: item,
              title: items[item].title,
          });
      }
      
      this.todos = newState;
      this.processing = false;
  });
}

Next, Call the above method from the ngOnInit method

ngOnInit() {
  this.getList();
}

The Firebase API offers us an incredibly easy way to not only grab this kind information from our database, but also to update us when new values get added to our database. It accomplishes this using the value custom event listener.

Remove Record

This method will be able to remove the data from the firebase database

delete(id) {
  this.firebaseService.remove(`/items/${id}`);    
}

After the above changes our component will looks like this

import { Component, OnInit } from '@angular/core';
import { Todo } from '../../todo';
import { FirebaseService } from 'src/app/services/firebase.service';

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

  todos: Todo[] = [];
  title: String = '';
  processing: boolean = true;

  constructor( private firebaseService: FirebaseService) { }

  ngOnInit() {
    this.getList();
  }

  getList() {
    const itemsRef = this.firebaseService.db('items');
    itemsRef.limitToLast(10).on('value', (snapshot) => {
        let items = snapshot.val();
        let newState = [];
        for (let item in items) {
            newState.unshift({
                id: item,
                title: items[item].title,
            });
        }
        
        this.todos = newState;
        this.processing = false;
    });
  }

  create() {

      const item = {
          title: this.title
      }
      this.title = '';
      const itemsRef = this.firebaseService.create('items', item);

  }

  delete(id) {
    this.firebaseService.remove(`/items/${id}`);    
  }

}

Running application:

Run application using ng serve --o and you should see firebase demo inside browser. Congrats!! See, it was easy.

Preview

Be First to Comment

Leave a Reply

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