Using AngularJS with Firebase for real-time applications

Loading

Firebase is a Backend-as-a-Service (BaaS) that provides real-time database capabilities, authentication, and cloud storage, making it an excellent choice for building real-time AngularJS applications.

This guide covers step-by-step integration of Firebase with AngularJS to create a real-time data-driven application.


1. Prerequisites

Before integrating Firebase with AngularJS, ensure you have:

  • Basic knowledge of AngularJS
  • A Firebase account
  • An AngularJS project set up

2. Setting Up Firebase

A. Create a Firebase Project

  1. Go to Firebase Console.
  2. Click on “Create a project”.
  3. Follow the setup wizard and click “Continue”.
  4. Once created, go to Project settings > General and copy your Firebase config object.

B. Enable Firebase Database

  1. Navigate to Build > Realtime Database in Firebase Console.
  2. Click “Create Database” and select a region.
  3. Set security rules to test mode (for development only).
  4. Note the database URL (e.g., https://your-project-id.firebaseio.com/).

3. Installing Firebase in AngularJS

A. Using CDN (Recommended for Quick Setup)

Add Firebase and AngularFire scripts in your index.html file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularfire/2.3.0/angularfire.min.js"></script>

B. Using NPM (For Node.js-based Projects)

npm install firebase angularfire

4. Configuring Firebase in AngularJS

A. Define AngularJS App and Firebase Configuration

Create an app.js file and initialize Firebase:

var app = angular.module('firebaseApp', ['firebase']);

app.config(function () {
var firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "your-project-id.firebaseapp.com",
databaseURL: "https://your-project-id.firebaseio.com/",
projectId: "your-project-id",
storageBucket: "your-project-id.appspot.com",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
};

// Initialize Firebase
firebase.initializeApp(firebaseConfig);
});

5. Using Firebase Realtime Database in AngularJS

A. Create an AngularJS Controller to Manage Data

Modify app.js to create a controller that interacts with Firebase:

app.controller('ChatController', function ($scope, $firebaseArray) {
var ref = firebase.database().ref().child("messages");

// Create a synchronized array
$scope.messages = $firebaseArray(ref);

// Function to send a message
$scope.sendMessage = function () {
if ($scope.newMessage) {
$scope.messages.$add({
text: $scope.newMessage,
timestamp: firebase.database.ServerValue.TIMESTAMP
});
$scope.newMessage = ""; // Clear input field
}
};
});

6. Creating the AngularJS View (HTML File)

Modify index.html to display real-time chat messages:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AngularJS + Firebase Chat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.6.1/firebase-database.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularfire/2.3.0/angularfire.min.js"></script>
<script src="app.js"></script>
</head>
<body ng-app="firebaseApp" ng-controller="ChatController">

<h2>Real-Time Chat</h2>
<ul>
<li ng-repeat="message in messages">
{{ message.text }} <small>({{ message.timestamp | date:'short' }})</small>
</li>
</ul>

<input type="text" ng-model="newMessage" placeholder="Type a message">
<button ng-click="sendMessage()">Send</button>

</body>
</html>

7. Explanation of Code

A. Firebase Initialization

  • firebase.initializeApp(firebaseConfig) initializes Firebase with the provided credentials.

B. Storing and Retrieving Messages

  • $firebaseArray(ref) creates a two-way data binding between Firebase and AngularJS.
  • $scope.messages automatically updates whenever new data is added to Firebase.

C. Sending Messages in Real-Time

  • $scope.sendMessage() adds a new message to Firebase.
  • firebase.database.ServerValue.TIMESTAMP stores the exact timestamp.
  • $scope.messages updates automatically without refreshing the page.

8. Adding Authentication with Firebase

A. Enable Firebase Authentication

  1. Go to Firebase Console > Authentication > Sign-in method.
  2. Enable Email/Password Authentication.

B. Implement User Authentication in AngularJS

Modify app.js:

app.controller('AuthController', function ($scope) {
$scope.login = function () {
firebase.auth().signInWithEmailAndPassword($scope.email, $scope.password)
.then((userCredential) => {
alert("Logged in successfully!");
})
.catch((error) => {
alert(error.message);
});
};

$scope.register = function () {
firebase.auth().createUserWithEmailAndPassword($scope.email, $scope.password)
.then((userCredential) => {
alert("Account created!");
})
.catch((error) => {
alert(error.message);
});
};
});

C. Update HTML for Authentication

<h2>Login</h2>
<input type="email" ng-model="email" placeholder="Email">
<input type="password" ng-model="password" placeholder="Password">
<button ng-click="login()">Login</button>
<button ng-click="register()">Register</button>

9. Deploying the Application

A. Using Firebase Hosting

  1. Install Firebase CLI: npm install -g firebase-tools
  2. Login to Firebase: firebase login
  3. Initialize Firebase in your project: firebase init
  4. Deploy the application: firebase deploy

Leave a Reply

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