delete auth user from firebase using angularfire2 | angularfire2 delete user

AngularFire smooths over the rough edges an Angular developer might encounter when implementing the framework-agnostic Firebase JS SDK & aims to provide a more natural developer experience by conforming to Angular conventions.

AngularFire

Install angular fire

ng add @angular/fire

If our authenticated user is not valid user then we want to delete it. We can delete authenticated user with two ways.

1. Using AngularFireAuth object

import { AngularFireAuth } from '@angular/fire/auth';
...
constructor(public auth: AngularFireAuth) {}
...

async deleteUser() {
    // 1. using auth
    (await this.auth.currentUser).delete();
}

2. Using firebase object

import firebase from 'firebase/app';
...
deleteUser() {
    // 2. using firebase
    firebase.auth().currentUser.delete()
}
...

If you imported firebase object like import * as firebase from 'firebase/app' then above code will not work. There is minor change in code.

import * as firebase from 'firebase/app';
...
deleteUser() {
    // 2. using firebase
    firebase.default.auth().currentUser.delete()
}
...

Final Code

import { Component } from '@angular/core';
import { AngularFireAuth } from "@angular/fire/auth";
import firebase from 'firebase/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() {
        // siginup with any provider
        this.auth.signInWithPopup(new firebase.auth.GoogleAuthProvider());
    }
    logout() {
        this.auth.signOut();
    }

    async deleteUser() {
        // 1. using auth
        (await this.auth.currentUser).delete();
        // 2. using firebase
        firebase.auth().currentUser.delete()
       // 3. if import is like import * as firebase from 'firebase/app';
       firebase.default.auth().currentUser.delete()
    }
}

If you are using AngularFire version above 6 then and want above code compatible with v6 api then need few change to make your.

  • import firebase from 'firebase/app to import firebase from 'firebase/compact/app';
  • import { AngularFireAuth } from "@angular/fire/auth to import { AngularFireAuth } from "@angular/fire/compact/auth

Leave a Reply