Angular 12 with Firebase 9

Quick Reference

Angular’s Docs have not been updated fully yet, so I made a quick reference.

app.module.ts – Imports

import { provideFirebaseApp, initializeApp }
from ‘@angular/fire/app’;
import { getAuth, provideAuth }
from ‘@angular/…



Quick Reference

Angular’s Docs have not been updated fully yet, so I made a quick reference.

app.module.ts – Imports

import { provideFirebaseApp, initializeApp } 
from '@angular/fire/app';
import { getAuth, provideAuth } 
from '@angular/fire/auth';
import { getFirestore, provideFirestore } 
from '@angular/fire/firestore';
import { getStorage, provideStorage } 
from '@angular/fire/storage';
import { getAnalytics, provideAnalytics } 
from '@angular/fire/analytics';


provideFirebaseApp(() => initializeApp(environment.firebase)),
provideFirestore(() => getFirestore()),
provideAuth(() => getAuth()),
provideStorage(() => getStorage()),
provideAnalytics(() => getAnalytics()),

import

import {
  collection,
  doc,
  docData,
  DocumentReference,
  Firestore,
  onSnapshot,
  query,
  where,
  Unsubscribe,
  Query,
  DocumentData,
  collectionData,
  collectionChanges,
  docSnapshots,
  ...
} from '@angular/fire/firestore';

constructor

constructor(
  private afs: Firestore
) { }



Documents

valueChanges()

docData<Post>(
  doc(this.afs, 'posts', id)
);

snapShotChanges()

docSnapshots<Post>(
  doc(this.afs, `posts/${id}`)
);



Collections

valueChanges()

collectionData<Post>(
  query(
    collection(this.afs, 'posts'),
    where('published', '==', true)
  ), { idField: 'id' }
);

snapShotChanges()

collectionChanges<Post>(
  query(
    collection(this.afs, 'posts'),
    where('published', '==', true)
  )
);



Auth

imports

import {
  Auth,
  signOut,
  signInWithPopup,
  user,
  signInWithEmailAndPassword,
  createUserWithEmailAndPassword,
  updateProfile,
  sendEmailVerification,
  sendPasswordResetEmail,
  getAdditionalUserInfo,
  OAuthProvider,
  linkWithPopup,
  unlink,
  updateEmail,
  updatePassword,
  User,
  reauthenticateWithPopup,
  ...
} from '@angular/fire/auth';



Code

constructor(private auth: Auth) {
  this.user$ = user(auth);
}

async getUser(): Promise<User | null> {
  return await this.user$.pipe(take(1)).toPromise();
}

...

async emailLogin(email: string, password: string)
: Promise<any> {
  return await signInWithEmailAndPassword(this.auth, email, password);
}

async emailSignUp(email: string, password: string)
: Promise<void> {

  const credential = await createUserWithEmailAndPassword(
    this.auth,
    email,
    password
  );
  await updateProfile(
    credential.user, { displayName: credential.user.displayName }
  );
  await sendEmailVerification(credential.user);

  // create user in db
  ...
}

async resetPassword(email: string): Promise<any> {

  // sends reset password email
  await sendPasswordResetEmail(this.auth, email);
  ...
}

async oAuthLogin(p: string): Promise<void> {

  // get provider, sign in
  const provider = new OAuthProvider(p);
  const credential = await signInWithPopup(this.auth, provider);
  const additionalInfo = getAdditionalUserInfo(credential);

  // create user in db
  if (additionalInfo?.isNewUser) {
    ...
  }
}



Storage

Import

import {
  Storage,
  ref,
  deleteObject,
  uploadBytes,
  uploadString,
  uploadBytesResumable,
  percentage,
  getDownloadURL,
  ...
} from '@angular/fire/storage';



Code

constructor(private storage: Storage) { }

async upload(
  folder: string,
  name: string,
  file: File | null
): Promise<string> {

  const ext = file!.name.split('.').pop();
  const path = `${folder}/${name}.${ext}`; {

  if (file) {
    try {
      const storageRef = ref(this.storage, path);
      const task = uploadBytesResumable(storageRef, file);
      this.uploadPercent = percentage(task);
      await task;
      const url = await getDownloadURL(storageRef);
    } catch(e: any) {
      console.error(e);
    }   
  } else {
    // handle invalid file
  }
  return url;
}

I may update this with more items, but I wanted to be particular to Angular and not get into the general Firebase 9 updates. I didn’t want to show every possible example, but you start to see the patterns.

J


Print Share Comment Cite Upload Translate
APA
Jonathan Gamble | Sciencx (2024-03-29T09:30:39+00:00) » Angular 12 with Firebase 9. Retrieved from https://www.scien.cx/2021/09/06/angular-12-with-firebase-9/.
MLA
" » Angular 12 with Firebase 9." Jonathan Gamble | Sciencx - Monday September 6, 2021, https://www.scien.cx/2021/09/06/angular-12-with-firebase-9/
HARVARD
Jonathan Gamble | Sciencx Monday September 6, 2021 » Angular 12 with Firebase 9., viewed 2024-03-29T09:30:39+00:00,<https://www.scien.cx/2021/09/06/angular-12-with-firebase-9/>
VANCOUVER
Jonathan Gamble | Sciencx - » Angular 12 with Firebase 9. [Internet]. [Accessed 2024-03-29T09:30:39+00:00]. Available from: https://www.scien.cx/2021/09/06/angular-12-with-firebase-9/
CHICAGO
" » Angular 12 with Firebase 9." Jonathan Gamble | Sciencx - Accessed 2024-03-29T09:30:39+00:00. https://www.scien.cx/2021/09/06/angular-12-with-firebase-9/
IEEE
" » Angular 12 with Firebase 9." Jonathan Gamble | Sciencx [Online]. Available: https://www.scien.cx/2021/09/06/angular-12-with-firebase-9/. [Accessed: 2024-03-29T09:30:39+00:00]
rf:citation
» Angular 12 with Firebase 9 | Jonathan Gamble | Sciencx | https://www.scien.cx/2021/09/06/angular-12-with-firebase-9/ | 2024-03-29T09:30:39+00:00
https://github.com/addpipe/simple-recorderjs-demo