Integrating AngularJS with Firebase

Loading

Firebase is a real-time backend service provided by Google that helps with authentication, database management, storage, and hosting. Integrating Firebase with AngularJS allows developers to build real-time, scalable web applications effortlessly.


1. Setting Up Firebase in an AngularJS App

Step 1: Create a Firebase Project

  1. Go to Firebase Console.
  2. Click “Add Project” and follow the setup process.
  3. Navigate to Project Settings > General > Your Apps.
  4. Click “Add Firebase to your web app” and copy the configuration.

Step 2: Add Firebase SDK to Your Project

Option 1: Use CDN (Recommended)

Include the Firebase and AngularFire scripts in your index.html file:

<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-auth.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-firestore.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.8.2/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angularfire/2.3.0/angularfire.min.js"></script>

Option 2: Install via npm

If you’re using a module bundler:

shCopyEditnpm install firebase angularfire --save

Step 3: Initialize Firebase in AngularJS

Add your Firebase configuration inside an AngularJS module:

var app = angular.module("myApp", ["firebase"]);

app.constant("FirebaseConfig", {
apiKey: "YOUR_API_KEY",
authDomain: "your-app.firebaseapp.com",
databaseURL: "https://your-app.firebaseio.com",
projectId: "your-app",
storageBucket: "your-app.appspot.com",
messagingSenderId: "YOUR_MESSAGING_SENDER_ID",
appId: "YOUR_APP_ID"
});

app.run(["FirebaseConfig", function(FirebaseConfig) {
firebase.initializeApp(FirebaseConfig);
}]);

2. Working with Firebase Realtime Database

Writing Data

Use $firebaseArray to interact with Firebase Realtime Database.

app.controller("MainController", function($scope, $firebaseArray) {
var ref = firebase.database().ref("users");
$scope.users = $firebaseArray(ref);

$scope.addUser = function() {
$scope.users.$add({
name: $scope.newUser.name,
age: $scope.newUser.age
});
$scope.newUser = {};
};
});

HTML

<div ng-app="myApp" ng-controller="MainController">
<input type="text" ng-model="newUser.name" placeholder="Enter Name">
<input type="number" ng-model="newUser.age" placeholder="Enter Age">
<button ng-click="addUser()">Add User</button>

<ul>
<li ng-repeat="user in users">{{ user.name }} ({{ user.age }} years old)</li>
</ul>
</div>

Data gets stored in Firebase Realtime Database! 🎉


Reading Data

Retrieve and display data dynamically.

$scope.users = $firebaseArray(firebase.database().ref("users"));

This keeps the users list in sync with Firebase.


Updating Data

$scope.updateUser = function(user) {
user.age = user.age + 1;
$scope.users.$save(user);
};

Deleting Data

$scope.deleteUser = function(user) {
$scope.users.$remove(user);
};

3. Firebase Authentication in AngularJS

User Registration with Email/Password

app.controller("AuthController", function($scope, $firebaseAuth) {
var auth = $firebaseAuth();

$scope.signUp = function() {
auth.$createUserWithEmailAndPassword($scope.email, $scope.password)
.then(function(user) {
console.log("User created: ", user);
})
.catch(function(error) {
console.log("Error: ", error.message);
});
};
});

HTML

<input type="email" ng-model="email" placeholder="Email">
<input type="password" ng-model="password" placeholder="Password">
<button ng-click="signUp()">Sign Up</button>

User Login

$scope.signIn = function() {
auth.$signInWithEmailAndPassword($scope.email, $scope.password)
.then(function(user) {
console.log("User signed in: ", user);
})
.catch(function(error) {
console.log("Login error: ", error.message);
});
};

User Logout

$scope.logout = function() {
auth.$signOut().then(function() {
console.log("User logged out");
});
};

Checking Auth State

auth.$onAuthStateChanged(function(user) {
if (user) {
console.log("User is logged in:", user);
} else {
console.log("User is logged out.");
}
});

4. Firebase Firestore (Cloud Database)

Firestore is a scalable NoSQL database alternative to Realtime Database.

Saving Data in Firestore

var db = firebase.firestore();
db.collection("users").add({
name: "Alice",
age: 25
});

Reading Data

db.collection("users").get().then((querySnapshot) => {
querySnapshot.forEach((doc) => {
console.log(doc.data());
});
});

5. Firebase Storage (File Uploads)

Uploading a File

$scope.uploadFile = function(file) {
var storageRef = firebase.storage().ref("images/" + file.name);
var uploadTask = storageRef.put(file);

uploadTask.on("state_changed",
function(snapshot) {
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log("Upload is " + progress + "% done");
},
function(error) {
console.log("Upload failed:", error);
},
function() {
uploadTask.snapshot.ref.getDownloadURL().then(function(downloadURL) {
console.log("File available at:", downloadURL);
});
}
);
};

6. Firebase Hosting (Deploy AngularJS App)

  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 your AngularJS app: firebase deploy

Leave a Reply

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