How to integrate Firebase with AngularJS

Loading

Integrating Firebase with AngularJS allows you to easily connect your AngularJS application to Firebase’s real-time database, authentication, and other Firebase services. This integration provides an easy way to handle real-time data, user authentication, and more within your AngularJS applications.

Here’s a step-by-step guide on how to integrate Firebase with AngularJS.

1. Setting Up Firebase

Before integrating Firebase into your AngularJS application, you need to set up a Firebase project:

Step 1: Create a Firebase Project

  • Go to Firebase Console.
  • Click on “Add Project” and follow the instructions to create a new Firebase project.

Step 2: Add Firebase to Your AngularJS App

  • After your Firebase project is created, go to the Firebase Console and click on your project.
  • In the Project settings, under “Your apps,” click the web icon to set up Firebase in your web application.
  • Copy the Firebase configuration object from the Firebase Console. It should look like this:
var firebaseConfig = {
apiKey: "YOUR_API_KEY",
authDomain: "YOUR_AUTH_DOMAIN",
databaseURL: "YOUR_DATABASE_URL",
projectId: "YOUR_PROJECT_ID",
storageBucket: "YOUR_STORAGE_BUCKET",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID",
measurementId: "YOUR_MEASUREMENT_ID"
};

2. Include Firebase SDK in Your AngularJS App

Step 1: Install Firebase

You need to include Firebase in your application. You can either use the CDN or install Firebase via npm (if you are using a build system like Webpack, Gulp, etc.).

Using CDN:

In your HTML file, add the Firebase script tags:

<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://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js"></script>
Or, Install with NPM:

If you’re using Node.js, install Firebase via npm:

npm install firebase

Then, import Firebase into your AngularJS application:

import firebase from 'firebase/app';
import 'firebase/database';
import 'firebase/auth';

3. Initialize Firebase in Your AngularJS App

After adding Firebase to your project, you need to initialize it with the Firebase configuration object you copied from the Firebase Console.

angular.module('myApp', [])
.run(function() {
// Initialize Firebase
firebase.initializeApp(firebaseConfig);
});

4. Creating a Firebase Service in AngularJS

It’s a good practice to create a service in AngularJS to interact with Firebase. This service will handle Firebase operations like reading and writing data to Firebase Realtime Database, and handling user authentication.

Step 1: Create Firebase Service

angular.module('myApp')
.service('FirebaseService', function($q) {

// Reference to Firebase Realtime Database
var database = firebase.database();

// Reference to Firebase Authentication
var auth = firebase.auth();

// Function to write data to Firebase
this.writeData = function(path, data) {
var deferred = $q.defer();
database.ref(path).set(data)
.then(function() {
deferred.resolve('Data written successfully');
})
.catch(function(error) {
deferred.reject('Error writing data: ' + error.message);
});
return deferred.promise;
};

// Function to read data from Firebase
this.readData = function(path) {
var deferred = $q.defer();
database.ref(path).once('value', function(snapshot) {
deferred.resolve(snapshot.val());
}, function(error) {
deferred.reject('Error reading data: ' + error.message);
});
return deferred.promise;
};

// Function to handle Firebase Authentication
this.signUp = function(email, password) {
var deferred = $q.defer();
auth.createUserWithEmailAndPassword(email, password)
.then(function(user) {
deferred.resolve(user);
})
.catch(function(error) {
deferred.reject(error.message);
});
return deferred.promise;
};

this.signIn = function(email, password) {
var deferred = $q.defer();
auth.signInWithEmailAndPassword(email, password)
.then(function(user) {
deferred.resolve(user);
})
.catch(function(error) {
deferred.reject(error.message);
});
return deferred.promise;
};

this.signOut = function() {
var deferred = $q.defer();
auth.signOut()
.then(function() {
deferred.resolve('Signed out successfully');
})
.catch(function(error) {
deferred.reject('Error signing out: ' + error.message);
});
return deferred.promise;
};

});

Step 2: Using Firebase Service in Controller

angular.module('myApp')
.controller('MainController', function($scope, FirebaseService) {

// Function to write data to Firebase
$scope.writeData = function() {
var data = { name: "John Doe", age: 30 };
FirebaseService.writeData('users/user1', data)
.then(function(message) {
console.log(message);
})
.catch(function(error) {
console.error(error);
});
};

// Function to read data from Firebase
$scope.readData = function() {
FirebaseService.readData('users/user1')
.then(function(data) {
console.log('Data from Firebase:', data);
})
.catch(function(error) {
console.error(error);
});
};

// User Authentication: Sign Up
$scope.signUp = function(email, password) {
FirebaseService.signUp(email, password)
.then(function(user) {
console.log('User signed up:', user);
})
.catch(function(error) {
console.error('Error signing up:', error);
});
};

// User Authentication: Sign In
$scope.signIn = function(email, password) {
FirebaseService.signIn(email, password)
.then(function(user) {
console.log('User signed in:', user);
})
.catch(function(error) {
console.error('Error signing in:', error);
});
};

// User Authentication: Sign Out
$scope.signOut = function() {
FirebaseService.signOut()
.then(function(message) {
console.log(message);
})
.catch(function(error) {
console.error(error);
});
};
});

5. HTML Template

In your HTML file, create input fields for the user to interact with the Firebase service (like sending and retrieving data, signing up, signing in, etc.).

<!DOCTYPE html>
<html ng-app="myApp">
<head>
<title>Firebase with AngularJS</title>
</head>
<body ng-controller="MainController">

<h1>Firebase Integration with AngularJS</h1>

<div>
<button ng-click="writeData()">Write Data</button>
<button ng-click="readData()">Read Data</button>
<div>{{ firebaseData }}</div>
</div>

<div>
<h2>Authentication</h2>
<input type="email" ng-model="email" placeholder="Email">
<input type="password" ng-model="password" placeholder="Password">
<button ng-click="signUp(email, password)">Sign Up</button>
<button ng-click="signIn(email, password)">Sign In</button>
<button ng-click="signOut()">Sign Out</button>
</div>

<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://www.gstatic.com/firebasejs/9.6.1/firebase-auth.js"></script>
<script src="app.js"></script>
</body>
</html>

Leave a Reply

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