You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular Firebase认证持久化设置报错:BrowserSessionPersistence需用new调用

解决Firebase认证持久化报错:Class constructor BrowserSessionPersistence cannot be invoked without 'new'

问题原因

你当前从@angular/fire/auth导入的browserLocalPersistence和browserSessionPersistence是类而非直接可用的持久化常量,调用setPersistence时会触发构造函数调用错误。

解决方案

从firebase/auth核心SDK导入正确的持久化常量,替换原导入路径即可:

修改后的完整代码

import { Injectable } from '@angular/core';
import { Auth, setPersistence, User, UserCredential, getAuth, signInWithEmailAndPassword, signOut } from '@angular/fire/auth';
// 从firebase/auth导入正确的持久化常量
import { browserLocalPersistence, browserSessionPersistence, Persistence } from "firebase/auth";
import { BehaviorSubject, Observable } from "rxjs";

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  loggedInUserEmail: string | null = ""
  errorMessage: string = ""
  isLoadingSubject: BehaviorSubject<boolean> = new BehaviorSubject(false)
  isLoading$: Observable<boolean> = this.isLoadingSubject.asObservable()
  
  constructor(private auth: Auth = getAuth()) {}
  
  async signIn(email: string, password: string, stayLoggedIn: boolean): Promise<void> {
    try {
      const persistence: Persistence = stayLoggedIn ? browserLocalPersistence : browserSessionPersistence
      this.isLoadingSubject.next(true)
      await setPersistence(this.auth, persistence)
      const userCredential: UserCredential = await signInWithEmailAndPassword(this.auth, email, password)
      this.loggedInUserEmail = userCredential.user.email
      console.log("Successfully signed in!")
    }
    catch(error: any) {
      if(error.code == "invalid-email" || error.code == "invalid-password") {
        this.errorMessage = "Helytelen e-mail vagy jelszó!"
      }
      else {
        this.errorMessage = "Valami hiba történt."
      }
      console.log(error.message)
    }
    finally {
      this.isLoadingSubject.next(false)
    }
  }
}

兼容方案(低版本AngularFire)

如果项目依赖的AngularFire版本较低,也可以直接传入字符串常量替代:

// 替换原persistence赋值行
const persistence = stayLoggedIn ? 'local' : 'session'

内容的提问来源于stack exchange,提问作者doomed4life

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 23:43:12