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.html 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

42 Comments

  1. lorenzo said:

    Great tutorial, first time I set firebase up with such simplicity!

    September 5, 2020
    Reply
  2. domoopelo said:

    pastillas viagra Eraveden cialis online ordering fradrady Order Cipro Online Supreme Suppliers

    December 12, 2020
    Reply
  3. order viagra said:

    I needed to draft you one little bit of observation so as to say thank you once again for those great methods you’ve documented here. It is quite pretty generous of people like you to deliver freely exactly what a number of people could possibly have made available as an e book to end up making some cash for themselves, even more so given that you could possibly have done it if you ever decided. These ideas also served like the fantastic way to comprehend other individuals have similar eagerness really like my personal own to realize much more when it comes to this matter. I believe there are several more pleasant sessions up front for people who scan your site. https://gemerekliler.com/

    January 7, 2021
    Reply
  4. endep tablets said:

    Thank you for each of your hard work on this web page. My aunt really likes going through investigations and it’s really obvious why. Most of us learn all of the lively method you offer practical strategies through this web site and even increase participation from some other people on the issue so our favorite girl is in fact learning a lot of things. Take advantage of the rest of the year. You are always doing a really good job. https://endepamitriptyline.com/

    January 8, 2021
    Reply
  5. paxil cheap said:

    I’m also commenting to let you be aware of of the excellent discovery my cousin’s child enjoyed checking your blog. She discovered a wide variety of details, most notably how it is like to have a great coaching character to get a number of people clearly completely grasp a number of advanced issues. You actually did more than her desires. I appreciate you for churning out such beneficial, dependable, edifying and cool guidance on that topic to Emily. https://paxilparoxetines.com/

    January 8, 2021
    Reply
  6. risperidone pills said:

    Thanks for your whole work on this website. My niece takes pleasure in working on research and it is simple to grasp why. We all notice all relating to the powerful ways you render vital tips and tricks via your website and therefore welcome response from website visitors on this theme while our own simple princess is without question understanding so much. Take pleasure in the rest of the year. Your performing a very good job. https://risniarisperidone.com/

    January 9, 2021
    Reply
  7. zyprexa no rx said:

    Thanks for the tips on credit repair on all of this blog. What I would advice people is to give up the mentality that they can buy now and pay later. As a society we tend to do this for many factors. This includes family vacations, furniture, plus items we really want to have. However, you must separate a person’s wants from the needs. When you’re working to fix your credit score you really have to make some trade-offs. For example you possibly can shop online to economize or you can click on second hand suppliers instead of highly-priced department stores to get clothing. https://zyprexaolanzapine.com/#

    January 9, 2021
    Reply
  8. buy seroquel said:

    I’m just commenting to let you be aware of of the exceptional discovery my cousin’s child enjoyed going through your blog. She discovered a wide variety of details, most notably how it is like to have a very effective coaching heart to get many more effortlessly fully understand certain extremely tough matters. You actually did more than my desires. I appreciate you for displaying such helpful, healthy, educational and also cool guidance on that topic to Evelyn. https://seroquelquetiapine.com/#

    January 9, 2021
    Reply
  9. https://www.vfv79.com/ said:

    Thank you! Yes, I enjoy step-by-step guides, too. They make learning a lot easier.
    After that you could contribute to the community by guest posting. You’ll have much more better results because people are already familiar with you.
    카지노사이트

    January 13, 2021
    Reply
  10. https://txt2080.com/ said:

    This makes commentators be more familiar with you + it helps you when building relationship with top bloggers.
    Something I learned from Danny Iny is that when you’re starting out, you need to be commenting on other blogs/forums and so on.
    모바일카지노

    January 13, 2021
    Reply
  11. https://liveone9.com/ said:

    Anyway, I like the way you presented the mistakes and how I could avoid them. I liked more the step-by-step guide to make helpful comments.
    Being social as a blogger is a great tip. Or, as I put it in “The Howdy Neighbor Technique” post I wrote over on Be A Better Blogger: be friendly! It goes a long way.
    온라인카지노

    January 13, 2021
    Reply
  12. riser 010 said:

    Thanks for the useful information on credit repair on your web-site. The thing I would offer as advice to people will be to give up a mentality they will buy at this moment and pay back later. As being a society most people tend to repeat this for many factors. This includes family vacations, furniture, plus items we really want to have. However, you must separate a person’s wants from the needs. When you’re working to fix your credit score you really have to make some trade-offs. For example you possibly can shop online to economize or you can click on second hand suppliers instead of highly-priced department stores to get clothing. https://allegrolokalnie.pl/oferta/riser-pci-e-008c-5w-mniej-od-009-najstabilniejszy-tnq

    January 16, 2021
    Reply
  13. Lynda said:

    I’ve been surfing online more than 4 hours today, yet I never found
    any interesting article like yours. It is pretty worth enough for me.
    In my view, if all web owners and bloggers made good content as you did,
    the net will be a lot more useful than ever before.

    My web site: cheap flights

    January 31, 2021
    Reply
  14. Lavonda said:

    I enjoy what you guys are up too. This type of clever work and
    coverage! Keep up the very good works guys I’ve incorporated you guys to my own blogroll.

    Also visit my homepage cheap flights

    February 1, 2021
    Reply
  15. Shaun said:

    You could definitely see your enthusiasm within the article
    you write. The sector hopes for more passionate writers like
    you who are not afraid to say how they believe. At all times follow your heart.

    Also visit my web blog … cheap flights

    February 1, 2021
    Reply
  16. Cecil said:

    Hello! I know this is somewhat off topic but I
    was wondering if you knew where I could locate a captcha plugin for
    my comment form? I’m using the same blog platform as yours and
    I’m having trouble finding one? Thanks a lot!

    my site … cheap flights, http://tinyurl.com,

    February 2, 2021
    Reply
  17. Frederick said:

    I could not refrain from commenting. Well written!

    my web blog cheap flights

    February 2, 2021
    Reply
  18. Christopher said:

    Howdy! This post could not be written any better! Reading this post reminds
    me of my previous room mate! He always kept chatting about this.
    I will forward this write-up to him. Fairly certain he
    will have a good read. Many thanks for sharing!

    my homepage: cheap flights (tinyurl.com)

    February 3, 2021
    Reply
  19. Aqcfgedecuddy said:

    order cialis online cheap generic cialis chennai cialis soft tablets

    February 5, 2021
    Reply
  20. FvfcGeste said:

    branded viagra without prescription viagra worldwide viagra australia no prescription

    February 6, 2021
    Reply
  21. Vito said:

    Howdy would you mind letting me know which web host you’re utilizing?
    I’ve loaded your blog in 3 different internet browsers and I
    must say this blog loads a lot faster then most. Can you suggest a good web hosting provider at
    a reasonable price? Thanks a lot, I appreciate it!

    Stop by my site cheap flights (tinyurl.com)

    February 12, 2021
    Reply
  22. Olive said:

    Hello, I do believe your blog may be having web browser compatibility issues.
    Whenever I take a look at your website in Safari, it looks fine but when opening in I.E., it
    has some overlapping issues. I merely wanted to
    give you a quick heads up! Besides that,
    great blog!

    Here is my web page … 카지노사이트

    February 14, 2021
    Reply
  23. Kvaxbype said:

    is one hour cash advance legit payday loan laws cash loan no credit check direct lender

    February 16, 2021
    Reply
  24. steveclarke said:

    Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your webpage? My blog is in the very same area of interest as yours and my visitors would certainly benefit from a lot of the information you provide here. Please let me know if this okay with you. Regards!| Life Experience Degrees

    February 19, 2021
    Reply
  25. clarkericky said:

    I appreciate, cause I found just what I was looking for. You have ended my four day long hunt! God Bless you man. Have a nice day. Bye Life Experience Degree

    February 19, 2021
    Reply

Leave a Reply

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