Skip to content

Use Firebase with Angular

Tyler Ruff edited this page Oct 25, 2022 · 7 revisions

Since Google makes Firebase and Angular, they have made it simple to use Firestore database elements with Angular, with the AngularFire libary.

  1. First, install AngularFire:
ng add @angular/fire
  1. Next, follow the prompts to automatically bootstrap your Angular application with the necessary config options. Open up app.module.ts, and add the following:
import { CommonModule } from '@angular/common';
...
imports: [
CommonModule
...

DONE! You now are ready to start setting up your desired Firebase service(s).

Firestore

  1. You can use it as follows, in any component:
import { Firestore, collectionData, collection } from '@angular/fire/firestore';
import { Observable } from 'rxjs';

interface Item {
 name: string,
 ...
};

@Component({
 selector: 'app-root',
 template: `
  <ul>
   <li *ngFor="let item of item$ | async">
    {{ item.name }}
   </li>
  </ul>
`
})
export class AppComponent {
 item$: Observable<Item[]>;
 constructor(firestore: Firestore) {
  const col = collection(firestore, 'items');
  this.item$ = collectionData(col) as Observable<Item[]>;
 }
}	
  1. You may also need to update the rules for your Firestore DB:
 rules_version = '2';
 service cloud.firestore {
  match /databases/{database}/documents {
   match /{document=**} {
    allow read;
    allow write: if request.auth.uid != null;
   }
  }
 }

Firebase Authentication

  1. Basic Usage
  • Add to your app.module.ts file:
...
import { FIREBASE_OPTIONS } from '@angular/fire/compat';
...
  providers: [
    { provide: FIREBASE_OPTIONS, useValue: environment.firebase }
  ],
...
  • Add to your component.html file:
import { Component } from '@angular/core';
import { AngularFireAuth } from '@angular/fire/compat/auth';
import firebase from 'firebase/compat/app';

@Component({
  selector: 'app-root',
  template: `
    <div *ngIf="auth.user | async as user; else showLogin">
      <h1>Hello {{ user.displayName }}!</h1>
      <button (click)="logout()">Logout</button>
    </div>
    <ng-template #showLogin>
      <p>Please login.</p>
      <button (click)="login()">Login with Google</button>
    </ng-template>
  `,
})
export class AppComponent {
  constructor(public auth: AngularFireAuth) {
  }
  login() {
    this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
  }
  logout() {
    this.auth.signOut();
  }
}
  1. Setup Persistence
import { PERSISTENCE } from '@angular/fire/compat/auth';

@NgModule({
  // ... Existing configuration
  providers: [
    // ... Existing Providers
    { provide: PERSISTENCE, useValue: 'session' },
  ]
})
export class AppModule { }
  1. Authenticated Route Guards
import { AngularFireAuthGuard } from '@angular/fire/compat/auth-guard';

export const routes: Routes = [
    { path: '',      component: AppComponent },
    { path: 'items', component: ItemListComponent, canActivate: [AngularFireAuthGuard] },
]

Sources

Clone this wiki locally