Angular 16 - Firebase 谷歌身份验证登录错误

问题描述 投票:0回答:1

我正在尝试仅使用 firebase 在 Angular 16 中使用 google 进行登录/登录。当我单击“登录”按钮时,出现以下错误:“错误错误:未捕获(承诺中):类型错误:无法读取未定义的属性(读取“GoogleAuthProvider”)”。我这样做是因为我找不到一种方法让 authState 用更简单的方法来控制用户是否登录。因此,如果您可以提供此错误的解决方案,或者提供一种使用公共警卫进行工作登录的方法(这样登录的用户无法访问登陆页面),那将会非常有帮助

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(['/']);
  }
}

问题出在这一行: constprovider = new firebase.auth.GoogleAuthProvider(); 它与 firebase 导入有关。

angular typescript firebase google-oauth angularfire
1个回答
0
投票

您正在尝试使用来自

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

相反,请尝试从

GoogleAuthProvider
导入
@firebase/auth

应该是这样的

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

...

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

...

© www.soinside.com 2019 - 2024. All rights reserved.