Encountering a Login Issue with Firebase Google Authentication in Angular 16

I am currently working on implementing a Google sign-in/login feature in Angular 16 using Firebase. However, when I try to click the "LogIn" button, I encounter the following error: "ERROR Error: Uncaught (in promise): TypeError: Cannot read properties of undefined (reading 'GoogleAuthProvider')". I opted for this approach as I couldn't find a simpler method to manage the authState and determine whether a user is logged in or not. Any assistance in resolving this error or providing an alternative solution for implementing a functional login with a public guard (ensuring that only logged-in users can access the landing page) would be greatly appreciated.

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';

import firebase from "firebase/compat/app";
import { AngularFireAuth } from '@angular/fire/compat/auth';
import { AngularFirestore, AngularFirestoreDocument } from '@angular/fire/compat/firestore';

import { Observable, of } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { User } from '../models/user.model';


@Injectable({
  providedIn: 'root'
})

export class AuthService {
  user$: Observable<User | null | undefined>;

  constructor(private afAuth: AngularFireAuth, private afs: AngularFirestore, private router: Router) {
    this.user$ = this.afAuth.authState.pipe(
      switchMap(user => {
          // Logged in
        if (user) {
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null);
        }
      })
    )
   }

   async googleSignin() {
    const provider = new firebase.auth.GoogleAuthProvider();
    const credential = await this.afAuth.signInWithPopup(provider);
    return this.updateUserData(credential.user);
  }

  private updateUserData(user) {
    const userRef: AngularFirestoreDocument<User> = this.afs.doc(`users/${user.uid}`);

    const data = { 
      uid: user.uid, 
      email: user.email, 
      displayName: user.displayName, 
      photoURL: user.photoURL
    } 
  }

  async signOut() {
    await this.afAuth.signOut();
    this.router.navigate(['/']);
  }
}

The issue seems to be related to the line: const provider = new firebase.auth.GoogleAuthProvider(); It appears to be a problem with the firebase import.

Answer №1

When implementing the sign-in feature, avoid using

new firebase.auth.GoogleAuthProvider()
from firebase/compat/app.

Instead, consider importing GoogleAuthProvider directly from @firebase/auth.

Make sure to follow this structure:

import firebase from "firebase/compat/app";
import { GoogleAuthProvider } from '@firebase/auth';

...

async signInWithGoogle() {
    const provider = new GoogleAuthProvider(); // Accessed from '@firebase/auth'
    const credentials = await this.afAuth.signInWithPopup(provider);
    return this.updateUserData(credentials.user);
}

...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Just incorporated Angular Material and Angular Animations into my project and encountered a slew of errors

After executing the command line: npm install --save @angular/material @angular/animations This snippet shows my package.json file: { "name": "cerpnew", "version": "0.0.0", "license": "MIT" ...

Encountering a compilation error while trying to utilize a union type in a function parameter within an

As stated on https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html, it is recommended to utilize multiple types for a parameter in a function (refer to the union part) /* OK */ interface Moment { utcOffset(): number; ...

Typescript implementation for structuring JSON response data from API calls

As a beginner in Typescript, I am eager to create a straightforward weather application using Firebase functions. One of the initial steps involves making an API call to fetch the current temperature of a particular city. Upon making the API call, the JSO ...

Tips for automatically scrolling the Google Maps view in a React application

After implementing the google-map-react package, I have designed a TypeScript MapView component with the following code snippet. export function MapView<I extends Mappable>({ getData }: MapViewProps<I>): JSX.Element { const [mapZoom, setMapZo ...

Trouble with the navbar collapse functionality in Bootstrap

3 I made some changes to the navbar, now the navbar-header is showing but the collapse navbar-collapse is not. Here is my code. Can you spot where I went wrong? <nav class="navbar navbar-default"> <div class="container-fluid" ...

Bold Chutzpah: Delving into AngularJS Testing using Jasmine and TypeScript

Currently, I am utilizing Angular 1.4.9 in combination with Jasmine 2.2.0 and Chutzpah 4.2.0. My Angular code and unit tests are both written in TypeScript within Visual Studio 2015 Update 1. The issue I am facing mirrors that which was previously discuss ...

In the function ngOnChange, the SimpleChange currentValue is supposed to be defined, but for some reason, the

Within the TypeScript code, a name variable is assigned input from another component. @Input() name : any ; In the ngOnChange function, I retrieve and print the SimpleChange object in the following manner. ngOnChanges(changes: SimpleChange){ console.l ...

There is no index signature that includes a parameter of type 'number' on the specified type xx

Here are the data types I am currently utilizing: export interface IHelpDeskTextData { supportPaneltext: ContactHelpdeskContex[]; selected?: number | null; brandOptions?: string[]; textPanel?: ITextPanel[]; } export class ContactHelpdeskContex { ...

Having trouble with SVG Circles - Attempting to create a Speedometer design

Trying to implement a speedometer in one of the components of my Vue project, but encountering an issue. When I input 0 into my progress calculation for determining the stroke fill, it overlaps with the background circle instead of staying within its bound ...

Allow Visual Studio Code to create a constructor for Typescript class

When developing Angular 2 apps in Typescript using Visual Studio Code, one common task is writing constructors with their parameter list. Is there a way to save time and effort on this? It would be really helpful if the IDE could automatically generate th ...

Running a function exclusively within a single div using Angular 2

I am currently using *ngFor to group items, and it's functioning correctly. However, I am having trouble displaying the "listofGroup" in the view even though it works in the console. Specifically, I need to run a function within a specific div in Angu ...

Tips for implementing logic on input values in Angular 4

How to increase a value from a form in app.component.html by 2 and display it <input type="number" class="form-control" [(ngModel)]="value" /> <!-- <p><button (click)="submit()" class="btn btn-warning btn-sm">Submit</button ...

Guide to implementing the patchValues() method in conjunction with the <mat-form-field> within the (keyup.enter) event binding

I am currently working on a feature that populates the city based on a zip code input. I have successfully achieved this functionality using normal HTML tags with the (keyup) event binding. However, when trying to implement it using CSS, I had to use (keyu ...

Issue with service injection within a singleton service in Angular2

Currently, I have two services in my application. ServiceA is non-singleton and provided to components through the Providers array, while ServiceB is a singleton that is listed in its module's Providers array. Both services work perfectly fine indepen ...

Issue stemming from reactivity causing difficulties with Vuex data mutation within actions

I have a Vuex store action that needs to interact with the API using new data for updating purposes. My goal is to create a separate object that mirrors an existing value in the store, allowing me to manipulate it without affecting reactivity. However, w ...

Angular 8: Setting the Default Dropdown Option to the Newest Value in the Updated ArrayList

I am currently working with Angular 8 and TypeScript. After calling a service and updating the array collection, I want to automatically select the last aggregated value. However, I always want the placeholder to be shown. How can I achieve this? <nb- ...

Refreshing Form in Angular 2

When I remove a form control from my form, it causes the form to always be invalid. However, if I delete a character from another input field and then add the same character back in (to trigger a change event), the form becomes valid as expected. Is ther ...

Issue with Angular 8 Animations when loading a module lazily - Encountered Synthetic Property Error

I currently have 2 different modules in my project, namely the app.module and a lazy.module. The lazy.module is specifically designed to be lazy loaded into the main app.module through routing mechanisms. const routes: Routes = [ { path: '', lo ...

Performing a conditional query on a Many-to-Many relationship in TypeORM

Operating under a many-to-many relationship between Category and Product entities In need of filtering products based on category ID Attempted to implement the following code after referring to some examples, but encountered difficulties in making it fun ...

What is the best way to convert this tsc script into an npm script in package.json?

I am looking to execute the following script as an npm script: tsc src/*.tsc --outDir bin When I run this command directly in the terminal, it works as expected. However, when I add the exact same script to my package.json: { "scripts": { ...