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

如何在单个Angular应用中用AngularFire连接两个Firebase项目?

AngularFire 7.5+ 多Firestore数据库连接实现

我需要为Angular应用连接第二个Firestore数据库,但现有旧方案不适用于AngularFire 7.5+的新注入语法。以下是当前的简化配置代码,求可行的实现方案:

当前配置代码

app.module.ts

import { environment } from '../environments/environment';

import { initializeApp,provideFirebaseApp } from '@angular/fire/app';
import { provideAuth,getAuth } from '@angular/fire/auth';
import { provideFirestore,getFirestore  } from '@angular/fire/firestore';

@NgModule({
  declarations: [
    AppComponent,
    HomeLayout
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    provideFirebaseApp(() => initializeApp(environment['firebase-proj-1'])),
    provideAuth(() => getAuth()),
    provideFirestore(() => getFirestore()),

  ],
  providers: [
    ScreenTrackingService,UserTrackingService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

environment.prod.ts

export const environment = {
  production: true,
  'firebase-proj-1': {
    projectId: 'xxx',
    appId: 'xxx',
    storageBucket: 'xxx',
    apiKey: 'xxx',
    authDomain: 'xxx',
    messagingSenderId: 'xxx',
    measurementId: 'xxx',
  },
  'firebase-proj-2': {
    apiKey: "xxx",
    authDomain: "xxx",
    projectId: "xxx",
    storageBucket: "xxx",
    messagingSenderId: "xxx",
    appId: "xxx",
    measurementId: "xxx"
  }
};

publications.service.ts

import { Injectable } from '@angular/core';
import { Firestore, collectionData, collection, 
          addDoc, QueryConstraint, query } from '@angular/fire/firestore';
import { orderBy } from 'firebase/firestore';

@Injectable({
  providedIn: 'root'
})
export class PubService {

  collectionPath = collection(this.firestore, 'publications')

  constructor( private firestore: Firestore ) { }

  getPubs(){
    const contraints:QueryConstraint[] = [orderBy('name', 'asc')]
    return collectionData(query(this.collectionPath, ...contraints), {idField: 'id'})
  }

  createPub(form: unknown){
    return addDoc(this.collectionPath, form)
  }

}

实现方案(AngularFire 7.5+)

步骤1:初始化第二个Firebase应用并配置Firestore提供者

在app.module.ts中,初始化第二个Firebase应用,并通过自定义注入令牌区分两个Firestore实例:

import { environment } from '../environments/environment';
import { InjectionToken, Inject } from '@angular/core';
import { initializeApp, provideFirebaseApp, FirebaseApp } from '@angular/fire/app';
import { provideAuth, getAuth } from '@angular/fire/auth';
import { provideFirestore, getFirestore, Firestore } from '@angular/fire/firestore';

// 定义第二个Firestore的注入令牌
export const SECONDARY_FIRESTORE = new InjectionToken<Firestore>('SecondaryFirestore');

@NgModule({
  declarations: [
    AppComponent,
    HomeLayout
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    // 初始化第一个Firebase应用
    provideFirebaseApp(() => initializeApp(environment['firebase-proj-1'])),
    provideAuth(() => getAuth()),
    provideFirestore(() => getFirestore()),
    // 初始化第二个Firebase应用(指定唯一名称避免冲突)
    provideFirebaseApp(() => initializeApp(environment['firebase-proj-2'], 'secondary-app')),
  ],
  providers: [
    ScreenTrackingService,
    UserTrackingService,
    // 提供第二个Firestore实例
    {
      provide: SECONDARY_FIRESTORE,
      useFactory: (app: FirebaseApp) => getFirestore(app),
      deps: [new Inject('secondary-app')]
    }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

步骤2:在服务中注入第二个Firestore实例

修改PubService,按需注入第二个Firestore实例:

import { Injectable, Inject } from '@angular/core';
import { Firestore, collectionData, collection, 
          addDoc, QueryConstraint, query } from '@angular/fire/firestore';
import { orderBy } from 'firebase/firestore';
import { SECONDARY_FIRESTORE } from '../app.module';

@Injectable({
  providedIn: 'root'
})
export class PubService {

  // 绑定第二个Firestore的集合
  collectionPath = collection(this.secondaryFirestore, 'publications')

  constructor(
    private firestore: Firestore, // 默认第一个Firestore实例
    @Inject(SECONDARY_FIRESTORE) private secondaryFirestore: Firestore // 第二个Firestore实例
  ) { }

  getPubs(){
    const contraints:QueryConstraint[] = [orderBy('name', 'asc')]
    return collectionData(query(this.collectionPath, ...contraints), {idField: 'id'})
  }

  createPub(form: unknown){
    return addDoc(this.collectionPath, form)
  }

}

关键说明

  • 初始化多Firebase应用时,必须为第二个及以后的应用指定唯一名称,避免实例冲突。
  • 通过InjectionToken可以精准区分不同的Firestore实例,确保注入对应数据库连接。
  • 无需全局替换默认Firestore,可根据业务需求在特定服务中按需注入第二个实例。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 11:22:25