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

AngularFire 7中Auth导入与AngularFireAuth注入问题排查

AngularFire 7 注入AngularFireAuth 报错解决

问题原因

报错NullInjectorError: 缺少InjectionToken angularfire2.app.options的提供者,核心原因是AngularFire 7彻底弃用了compat兼容模式的导入与配置方式,且未正确配置Firebase应用选项的提供者。

解决步骤

1. 切换至新模块导入

  • 卸载compat兼容包(若已安装):
    npm uninstall @angular/fire/compat
    
  • 在app.module.ts中替换旧的compat导入为新的函数式模块:
    import { provideFirebaseApp, initializeApp } from '@angular/fire/app';
    import { provideAuth, getAuth } from '@angular/fire/auth';
    

2. 配置Firebase应用与Auth提供者

在app.module.ts的providers数组中添加Firebase配置和Auth服务提供者,替换旧的AngularFireModule.initializeApp()写法:

@NgModule({
  declarations: [AppComponent],
  imports: [BrowserModule],
  providers: [
    // 初始化Firebase应用
    provideFirebaseApp(() => initializeApp({
      apiKey: '你的API密钥',
      authDomain: '你的Auth域名',
      projectId: '你的项目ID',
      storageBucket: '你的存储桶地址',
      messagingSenderId: '你的消息发送者ID',
      appId: '你的应用ID'
    })),
    // 提供Auth服务实例
    provideAuth(() => getAuth())
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

3. 更新LoginService的注入逻辑

不再从compat包导入AngularFireAuth,直接注入新的Auth实例并使用对应的Firebase Auth函数:

import { Injectable } from '@angular/core';
import { Auth, signInWithEmailAndPassword } from '@angular/fire/auth';

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  constructor(private auth: Auth) { }

  login(email: string, password: string) {
    return signInWithEmailAndPassword(this.auth, email, password);
  }
}

重要提示

AngularFire 7采用函数式提供者模式,所有Firebase服务都需通过provideXxx函数注册到依赖注入系统中,不再支持旧版本的模块导入与初始化方式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 11:10:32