Using Firebase Realtime Database from Angular

In the app's main module, import and initialize the core and Realtime Database modules from AngularFire, pulling the Firebase config from the environment config.

import {AngularFireModule} from '@angular/fire';
import {AngularFireDatabaseModule} from '@angular/fire/database';
import {database} from 'firebase/app';
import {environment} from 'src/environments/environment';
...
// in the NgModule imports
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,

AngularFireDatabase can then be injected anywhere it's needed, most commonly in a service since you should use [Angular Services as Your Single Source of Truth].

const DB_PREFIX = environment.production ? '/prod-v1' : '/dev-v1';
const FIREBASE_DB_PATHS = {
  CHAT_MESSAGES: `/${DB_PREFIX}/chat/messages`,
};

// the shape of items to store
type FireDbEntry = {
  author: string;
  msg: string;
  updatedAt: number;
};

class MyService {
  chatMessages$: Observable<FireDbEntry[]|null>;

  constructor(
    private readonly fireDb: AngularFireDatabase,
  ) {
    const db = FIREBASE_DB_PATHS.CHAT_MESSAGES;
    this.chatMessages$ = fireDb.list<FireDbEntry>(db).valueChanges();
  }

  sendChatMessage(author: string, msg: string) {
    this.fireDb.list(dbPath).push({
      author,
      msg,
      updatedAt: database.ServerValue.TIMESTAMP,
    });
  }
}

Related APIs

  • fireDb.list(dbPath).valueChanges() is an observable of real-time database changes as an array of items
  • fireDb.object(dbPath).valueChanges() will return the same data as a hash
    • I assumed it's keyed by entry id
  • fireDb.object(dbPath).set(newObj) will overwrite the data at the path