Using Firebase with Angular 11

Using Firebase With Angular

As a web developer , it is an absolute necessity to be able to develop a robust application with a secure/stable backend integrated to a robust front-end framework. However, the requirement of implementing a backend is often considered to be time-confusing, therefore a potential option might be to use Firebase (a backend on its own). Firebase offers developers an authentication service, storage service (to manage files on the server), hosting (static host) and a Realtime Database (along with FireStore) to manage data of your robust application.

Considering these services offered, integrating Firebase as a backend to your web app takes away all the code when it comes to implementing a backend. All that is required is a client side SDK that can be used to communicate with the backend to authenticate, store files and user data.

In this walkthrough, I will provide instructions on configuring Angular on your system as well as integrating Firebase to the Angular Application and perform operations on Firebase Realtime Database such as Inserting, Retrieving Data, with finally deploying the Angular Application to firebase hosting.

Step 1) Installing the Angular CLI

In order to create an Angular project, the Angular CLI must be installed on the development system. To do so, Node.js must be installed.

Follow the URL to install Node.js on your development environment

Run the command stated below on a terminal to install the Angular CLI.

npm install -g @angular/cli

Step 2) Creating an Angular Project

To get started, lets create a fresh Angular Project by typing the command below (on a terminal) with the project name “FirebaseIntegration”.

ng new FirebaseIntegration

Follow the steps provided by the Angular CLI.

  • Do not enforce stricter type checking.
  • Do not include included routing.
  • Use CSS as the styling language.
Figure 1. Project Setup

Step 3) Adding Firebase to the Angular Project

After the Angular CLI finishes creating the project, head over to the Firebase Console and create a project on the Firebase Console without enabling Google Analytics.

After creating the Firebase Project, create an integration for the web application by clicking on the “Web” icon.

Provide a suitable name for your application to register the application, and copy the object firebaseConfig .

Next, head over to your new Angular Project and open the environment.prod.ts file and paste the firebaseConfig object to the existing object so that your output looks similar to the diagram illustrated below.

Copied Object from Firebase Console:

firebaseConfig = {
apiKey: “<<your data>>”,
authDomain: “<<your data>>”,
projectId: “<<your data>>”,
storageBucket: “<<your data>>”,
messagingSenderId: “<<your data>>”,
appId: “<<your data>>”
};

Pasted Outcome:

export const environment = {
production: true,
firebaseConfig: {
apiKey: “<<your data>>”,
authDomain: “<<your data>>”,
projectId: “<<your data>>”,
storageBucket: “<<your data>>”,
messagingSenderId: “<<your data>>”,
appId: “<<your data>>”,
};

After pasting the configuration data successfully, open up a terminal inside the project directory and enter the following command to initialize the Angular Application with Firebase using the @Angular/fire library.

ng add @angular/fire

This will install the required npm modules and the Angular CLI with walk you through the configuration process.

This process will require you to select a Firebase project, make sure to click the on the project you created for this article.

Upon completion of this process, open up the app.module.ts to add the relevant AngularFire modules that will be used in this tutorial.

  1. AngularFireModule
  2. AngularFireDatabaseModule

The AngularFireModule has a static method initializeApp() that accepts the firebaseConfig object that was stored in the environment.prod.ts .

Your output should be as below.

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';import { AngularFireModule } from '@angular/fire';
import { AngularFireDatabaseModule } from '@angular/fire/database';
import { environment } from 'src/environments/environment.prod';@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebaseConfig),
AngularFireDatabaseModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

After doing so, run the following command to build the Angular Project.

ng serve

Now that we have successfully added firebase to the Angular Application, lets work on the app.component.html for demonstration purposes of the Realtime Database.

Step 4) Saving Data on Firebase using Angular Application

1.Visit http://localhost:4200/ to open the Angular Application.

2. Lets inject the AngularFireDatabase to the app.component.ts to use the Client side SDK of the Firebase Realtime Database.

constructor(private db: AngularFireDatabase) { }

3. Lets setup a input field with a button to submit data to database upon button click.

<div class=”custom”>
<input type=”text” class=”formats” placeholder=”Enter Demo Text Here…” #input>
<button class=”btn” type=”button” (click)="saveData(input.value)">Save Data</button>
</div>

4. Add CSS to the fields in the app.component.css.

.custom {
width: 50%;
text-align: center;
}
.formats{
width: 100%;
padding: 10px;
}
.btn{
padding:10px;
margin-top: 5px;
background-color: lightgreen;
width: 60%;
}
.btn:hover{
cursor: pointer;
}

5. Declare Method saveData(inputValue:string) in app.component.ts

This method will push the entered data onto the Realtime Database of the configured Firebase Project and will generate a unique ID for the Data submitted as well.

6. Create the Realtime Database from the Firebase Console.

Navigate over to your Firebase Console and create the Realtime Database with us-central1 as database location and set up in test mode since we are not configuring authentication on this tutorial.

After doing this, head over to your Angular Application and enter some data to your input field and click on the submit and observe the database to watch your data get stored on Firebase!

Data Saved using Angular Application.
Data Provided by Angular Application.

Step 5) Retrieving Data Stored on Firebase

The AngularFireDatabase service provides methods of retrieving data stored on the Realtime Database as an observable . To make use of this, a subscription to the observable valueChanges() on the ngOnInit() lifecycle method so that the AppComponent listens to changes made on a node of a Realtime Database.

This can be done as illustrated below.

Subscription to the Node of the Realtime Database

This method will keep listening to changes made on the data of the items node of the Realtime Database and will display the data on that node whenever a value on the node changes.

Now that we retrieve data from Firebase, lets display it to the client.

This can be done by creating a list group and attaching each item to a list item via an ngFor loop.

<div class="custom">
<input type="text" class="formats" placeholder="Enter Demo Text Here…" #input>
<button class="btn" type="button" (click)="saveData(input.value)">Save Data</button>
<hr>
<ul>
<li *ngFor="let item of data"> {{item}} </li>
</ul>
</div>

Whenever new data is added to the list data the client app will be updated accordingly.

Sample Output

To test this out, try saving data and observe the list changing accordingly.

Step 6) Deploying Application to Firebase

Now that we have successfully setup data transmission across Firebase, we are finally ready to deploy our application to firebase so that it can be accessed by users all over the globe.

To do so we have to follow these steps.

  1. Stop currently running Angular Server
  2. Run ng build --prod to build application for production
  3. Setup Firebase Hosting on the Firebase Console
  4. Run ng deploy to deploy Angular Application to Firebase

After stopping the locally running server, execute the command ng build --prod to build an optimized single page JavaScript application that is ready for deployment on a Static Host such as Firebase.

After doing so, head over to the Firebase Project and navigate to hosting and click on “Get Started” to configure hosting. Since we have already configured Firebase to our Angular Project we can click “next” to the steps and once executed successfully, you will see a list of domains.

Now that we have done steps 1–3, we can run the command ng deploy . This will take the files generated by ng build --proud and will upload those files to the Static Host and Firebase will generate a unique URL that can be used to access the website on the internet.

Once the deploy has been completed, you can see this.

Deploy Process — ng deploy

Step 2 can ideally be skipped as running ng deploy automatically executes the ng build --prod command.

After the deploy has been completed, you can access the hosting URL to view your new web application that is now capable of saving and retrieving data!

Conclusion

Firebase can do a lot more with Angular. This was just a basic walkthrough on the ways you can utilize Firebase to Save, Retrieve Data from Realtime Database and also an introduction to using Hosting.

You can perform more functions like include Authentication by using Firebase Auth and upload files by using Firebase Storage and even use Firebase Cloud Functions to perform a computational process on the Google Cloud Platform.

This sample project can be visited through the URL: https://fir-integration-b4929.web.app/

The GitHub repo for this project can be accessed via: https://github.com/lakindu2002/FirebaseIntegration

And as always, more information about the @Angular/fire SDK can be found by reading the official documentation.

Final Year Undergraduate following Software Engineering at Staffordshire University with knowledge in Java, C#, Angular 11 and Node.js using AWS Serverless.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store