firebase AngularFire Auth Persistence不能在没有'new'的情况下调用

bcs8qyzn  于 2023-11-21  发布在  Angular
关注(0)|答案(3)|浏览(169)

我尝试在angularfire中使用persistence来实现以下代码:

constructor(private auth: Auth, private router: Router) {
    if (auth.currentUser) this.router.navigate(this.redirect);
  }

  async loginWithGoogle() {
    const provider = new GoogleAuthProvider();

    try {
      await setPersistence(this.auth, browserLocalPersistence);
      await signInWithPopup(this.auth, provider);
      this.message = 'Sign in successful';
      await this.router.navigate(this.redirect);
    } catch (error: any) {
      console.error(error);
      if (error.code) {
        this.message = `${error.code}: ${error.message}`;
      } else {
        this.message = 'There was a problem signing in. Please try again.';
      }
    }
  }

字符串
然而,我总是得到这个错误,无论setPersistence方法的位置如何:

Class constructor BrowserLocalPersistence cannot be invoked without 'new'


我按照文档(https://firebase.google.com/docs/auth/web/auth-state-persistence)到T;我做错了什么?
我使用的是Angular 13、Angularfire 7和Firebase 9。

oaxa6hgo

oaxa6hgo1#

我经历过这个确切的问题-不清楚原因,但我发现,如果我直接从firebase库导入方法,我可以解决它们。
具体来说,我导入这些功能如下:

import { browserLocalPersistence,browserSessionPersistence, setPersistence } from 'firebase/auth';

字符串
而不是从'@angular/fire/auth'
然后它就完美地工作了(就像在一个普通的JavaScript应用程序中一样)。

jrcvhitl

jrcvhitl2#

persisting auth state persistence in the JavaScript/web SDK的文档中:
对于Web应用程序,默认行为是即使在用户关闭浏览器之后也保持用户的会话。
我强烈建议只有在你知道你有一个特定的用例需要它的时候才调用setPersistence。在大多数浏览器上,Firebase已经在重新加载之间持久化了auth状态,而不调用setPersistence

1dkrff03

1dkrff033#

我已经离开了我的实现登录与供应商下面。
虽然我在这个项目中还没有迁移到Modular Firebase V9,但身份验证持久化仍然可以正常工作--登录过一次的用户不需要每次回来都重新登录。
我发现在服务中保留认证逻辑是一个很好的做法,可以将其注入到组件或模块中。
在构造器中,您可以找到一种很好的方法来确定您的用户是否已登录,并且在Cloud Firestore中具有与其auth ID相关联的配置文件。

export class AuthService {

  analytics = firebase.analytics(); // this declaration works better than constructor init from import
  userCredential; // to store the promise returned when signing up/ in with email & password
  // type: User from the model
  user$: Observable<User>; // defined as observable as it can change when user signs in/out

  constructor(
    // inject imports for fire store auth service in constructor
    private afAuth: AngularFireAuth,
    private afs: AngularFirestore,
    private router: Router
  ) {

    // Get the auth state, then fetch the Firestore user document or return null
    this.user$ = this.afAuth.authState.pipe(  // define the observable state
      switchMap(user => {
        // Logged in
        if (user) { // if user is defined
          // point to document with matching ID
          return this.afs.doc<User>(`users/${user.uid}`).valueChanges();
        } else {
          // Logged out
          return of(null); // allows us to tell when user is not logged in
        }
      })
    );
  }

  /**
   * Authenticate users with Google O-Auth provider
   * @param {boolean=} [registration = false] - whether this is the first sign in or not
   */
  async googleSignIn(registration: boolean = false) {

    // reference google auth provider
    const provider = new auth.GoogleAuthProvider();
    // pass provider to sign in with popup functionality
    this.userCredential = await this.afAuth.signInWithPopup(provider);

    if (registration) { // if the request is coming from the registration page

      try {
        await this.insertNewUser(this.userCredential.user, this.userCredential.user.displayName);
        await this.verifyEmail(); // send a verification email to the user when registering
        await this.router.navigate(['/user-profile']);
      } catch (err) {
        console.log(`Error: ${err.errorMessage}`);
        M.toast({html: `Error: ${err.errorMessage}`, classes: 'rounded materialize-red'});
      }

    } else {  //  user is logging in again

      try {
        await this.router.navigate(['/user-profile']);
        M.toast({html: `Signed in as ${this.userCredential.user.displayName}`, classes: 'rounded blue'});

        // let user know that they haven't been verified
        if (!this.userCredential.emailVerified) {
          console.log(`user's email has not been verified`);
          M.toast({
            html: `Your email has not yet been verified. Please check your inbox.`,
            classes: 'rounded orange darken-2'
          });
        }

      } catch (err) {
        console.log(`Error: ${err.errorMessage}`);
        M.toast({html: `Error: ${err.errorMessage}`, classes: 'rounded materialize-red'});
      }

    }

    // track the login event with analytics
    this.analytics.logEvent('login', {serviceName: 'Google Login'});

  } // end of sign in function

} // end of auth service

字符串

相关问题