Bird
Raised Fist0
Firebasecloud~10 mins

Firebase with Angular - Commands & Configuration

Choose your learning style10 modes available
Introduction
Firebase is a platform that helps you add backend features like databases and authentication to your Angular app without managing servers. It solves the problem of building and scaling app backends easily.
When you want to add user login and registration to your Angular app quickly.
When you need a real-time database that updates your app instantly.
When you want to host your Angular app with a global content delivery network.
When you want to send push notifications to your Angular app users.
When you want to track app usage and errors without setting up complex tools.
Config File - angular.json
angular.json
{
  "$schema": "https://json.schemastore.org/angular-cli.json",
  "version": 1,
  "projects": {
    "my-angular-app": {
      "projectType": "application",
      "schematics": {},
      "root": "",
      "sourceRoot": "src",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "dist/my-angular-app",
            "index": "src/index.html",
            "main": "src/main.ts",
            "polyfills": "src/polyfills.ts",
            "tsConfig": "tsconfig.app.json",
            "assets": ["src/favicon.ico", "src/assets"],
            "styles": ["src/styles.css"],
            "scripts": []
          },
          "configurations": {
            "production": {
              "fileReplacements": [
                {
                  "replace": "src/environments/environment.ts",
                  "with": "src/environments/environment.prod.ts"
                }
              ],
              "optimization": true,
              "outputHashing": "all",
              "sourceMap": false,
              "extractCss": true,
              "namedChunks": false,
              "extractLicenses": true,
              "vendorChunk": false,
              "buildOptimizer": true
            }
          }
        }
      }
    }
  },
  "defaultProject": "my-angular-app"
}

This is the Angular workspace configuration file. It defines the build settings for your Angular app named my-angular-app. It tells Angular CLI how to build and serve your app files.

Commands
This command installs Firebase and AngularFire libraries needed to connect your Angular app with Firebase services.
Terminal
npm install firebase @angular/fire --save
Expected OutputExpected
+ firebase@9.22.1 + @angular/fire@7.5.0 added 50 packages from 30 contributors and audited 120 packages in 5.2s found 0 vulnerabilities
This command sets up AngularFire in your Angular project, including adding Firebase configuration and updating app modules.
Terminal
ng add @angular/fire
Expected OutputExpected
Installing packages for tooling via npm. Installed packages for tooling via npm. ✔ Packages installed successfully. ✔ Added Firebase configuration to environment files. ✔ Added AngularFireModule to AppModule.
This command builds and runs your Angular app locally so you can test Firebase integration in your browser.
Terminal
ng serve
Expected OutputExpected
✔ Compiled successfully. ** Angular Live Development Server is listening on localhost:4200, open your browser on http://localhost:4200/ ** Date: 2024-06-01T12:00:00.000Z - Hash: abcdef1234567890 - Time: 5000ms ✔ Browser application bundle generation complete.
This command uploads your built Angular app to Firebase Hosting so it is available on the internet.
Terminal
firebase deploy --only hosting
Expected OutputExpected
=== Deploying to 'my-angular-app'... i deploying hosting i hosting: preparing public directory 'dist/my-angular-app' ✔ hosting: files prepared for upload i hosting: uploading files ✔ hosting: files uploaded successfully ✔ Deploy complete! Project Console: https://console.firebase.google.com/project/my-angular-app/overview Hosting URL: https://my-angular-app.web.app
→
--only hosting - Deploys only the hosting part of Firebase, skipping other services.
Key Concept

If you remember nothing else from this pattern, remember: AngularFire connects your Angular app to Firebase services easily by installing libraries, configuring modules, and deploying your app.

Common Mistakes
Not installing both firebase and @angular/fire packages before setup
AngularFire depends on both packages; missing one causes errors when importing or running the app.
Always run 'npm install firebase @angular/fire --save' before adding AngularFire to your project.
Skipping the 'ng add @angular/fire' command and manually adding config
Manual setup can miss important module imports and environment updates, causing runtime errors.
Use 'ng add @angular/fire' to automate configuration and ensure all necessary changes are made.
Trying to deploy without building the Angular app first
Firebase Hosting needs the built files in the 'dist' folder; without building, deploy fails or serves empty content.
Run 'ng build --prod' or 'ng serve' to build your app before deploying.
Summary
Install Firebase and AngularFire libraries to connect Angular with Firebase.
Use 'ng add @angular/fire' to configure Firebase in your Angular app automatically.
Run 'ng serve' to test locally and 'firebase deploy --only hosting' to publish your app online.

Practice

(1/5)
1. What is the main purpose of integrating Firebase with an Angular application?
easy
A. To run Angular code on the Firebase server
B. To replace Angular's core framework features
C. To provide backend services like database and authentication easily
D. To create static HTML pages without JavaScript

Solution

  1. Step 1: Understand Firebase's role

    Firebase offers backend services such as real-time database and user authentication.
  2. Step 2: Understand Angular's role

    Angular is a frontend framework that can use Firebase to add backend features easily.
  3. Final Answer:

    To provide backend services like database and authentication easily -> Option C
  4. Quick Check:

    Firebase adds backend services to Angular apps = D [OK]
Hint: Firebase adds backend features to Angular apps fast [OK]
Common Mistakes:
  • Thinking Firebase replaces Angular framework
  • Believing Firebase runs Angular code on server
  • Confusing Firebase with static site generator
2. Which is the correct way to initialize Firebase in an Angular app's app.module.ts file?
easy
A. const app = firebase.initializeApp(firebaseConfig);
B. import { initializeApp } from 'firebase/app'; const app = initializeApp(firebaseConfig);
C. import firebase from 'firebase'; firebase.init(firebaseConfig);
D. firebaseApp = new Firebase(firebaseConfig);

Solution

  1. Step 1: Check Firebase modular SDK usage

    Firebase v9+ uses modular imports like initializeApp from 'firebase/app'.
  2. Step 2: Verify correct initialization syntax

    The correct syntax is const app = initializeApp(firebaseConfig); after importing.
  3. Final Answer:

    import { initializeApp } from 'firebase/app'; const app = initializeApp(firebaseConfig); -> Option B
  4. Quick Check:

    Use modular import and initializeApp() = A [OK]
Hint: Use modular import and initializeApp() for Firebase v9+ [OK]
Common Mistakes:
  • Using old namespace import like 'firebase.initializeApp'
  • Calling non-existent method 'firebase.init'
  • Trying to create Firebase instance with 'new Firebase()'
3. Given this Angular Firebase code snippet, what will be the output in the console?
import { getAuth, signInWithEmailAndPassword } from 'firebase/auth';

const auth = getAuth();
signInWithEmailAndPassword(auth, 'user@example.com', 'wrongpass')
  .then(() => console.log('Login success'))
  .catch(error => console.log(error.code));
medium
A. 'auth/wrong-password'
B. 'Login success'
C. 'auth/user-not-found'
D. SyntaxError

Solution

  1. Step 1: Understand signInWithEmailAndPassword behavior

    This function tries to sign in with given email and password, returns a promise.
  2. Step 2: Analyze given credentials

    The password is 'wrongpass', which is incorrect, so sign-in fails and triggers catch.
  3. Step 3: Check error code logged

    The catch logs error.code, which for wrong password is 'auth/wrong-password'.
  4. Final Answer:

    'auth/wrong-password' -> Option A
  5. Quick Check:

    Wrong password error code = 'auth/wrong-password' [OK]
Hint: Wrong password triggers 'auth/wrong-password' error code [OK]
Common Mistakes:
  • Assuming success message logs on wrong password
  • Confusing 'user-not-found' with wrong password error
  • Expecting syntax error from correct code
4. You wrote this code in your Angular component to fetch Firestore data but get an error:
import { getFirestore, collection, getDocs } from 'firebase/firestore';

const db = getFirestore();
const usersCol = collection(db, 'users');
const userSnapshot = await getDocs(usersCol);
const userList = userSnapshot.docs.map(doc => doc.data());
console.log(userList);

What is the likely cause of the error?
medium
A. Missing async function to use await
B. Firestore collection name 'users' is invalid
C. getDocs does not exist in firebase/firestore
D. doc.data() returns undefined always

Solution

  1. Step 1: Identify usage of await

    The code uses await getDocs(usersCol) which requires an async function context.
  2. Step 2: Check for async function wrapper

    If this code is not inside an async function, it will cause a syntax or runtime error.
  3. Final Answer:

    Missing async function to use await -> Option A
  4. Quick Check:

    await must be inside async function = B [OK]
Hint: Use await only inside async functions [OK]
Common Mistakes:
  • Assuming collection name 'users' is invalid
  • Thinking getDocs is not part of Firestore SDK
  • Believing doc.data() returns undefined always
5. You want to display a real-time list of messages in your Angular app using Firebase Firestore. Which approach correctly sets up a subscription to update the list automatically when data changes?
import { getFirestore, collection } from 'firebase/firestore';
import { collectionData } from 'rxfire/firestore';

const db = getFirestore();
const messagesCol = collection(db, 'messages');

// What should you do next?
hard
A. Use messagesCol.onSnapshot() without import
B. Call getDocs(messagesCol) once and assign to messages
C. Use collectionData(messagesCol).then(data => this.messages = data);
D. Use collectionData(messagesCol).subscribe(data => this.messages = data);

Solution

  1. Step 1: Understand real-time updates with Firestore

    Firestore supports real-time listeners that update data when changes occur.
  2. Step 2: Use RxFire's collectionData for Angular

    RxFire's collectionData returns an observable you can subscribe to for live updates.
  3. Step 3: Correct subscription syntax

    Using collectionData(messagesCol).subscribe(data => this.messages = data); sets up real-time updates properly.
  4. Final Answer:

    Use collectionData(messagesCol).subscribe(data => this.messages = data); -> Option D
  5. Quick Check:

    Subscribe to collectionData observable for real-time updates = C [OK]
Hint: Subscribe to collectionData observable for live Firestore updates [OK]
Common Mistakes:
  • Using getDocs for one-time fetch instead of real-time
  • Calling onSnapshot without proper import or context
  • Using then() on observable instead of subscribe()
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard