如何在 AngularFire 中访问非默认 Firestore 数据库

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

我正在尝试访问我的 gcloud 项目中的另一个 firestore 数据库。我可以很好地访问默认的(默认),但我无法访问一个名为“开发”的项目,并且无法在网上找到任何有关如何访问它的文档。

当我获得初始 Firebase 配置时,它不包含数据库 URL,但我添加了一个来尝试访问数据库,但它不起作用。这就是我的配置目前的样子

export const firebaseConfig = {
  apiKey: <apiKey>,
  authDomain: <authDomain>,
  projectId: <projectId>,
  storageBucket: <storageBucket>,
  messagingSenderId: <messagingSenderId>,
  appId: <appId>,
  databaseURL: "https://firestore.googleapis.com/v1/projects/<projectId>/databases/development/",
  measurementId: <measurementId>,
  databaseId: "development",
};

export const environment = {
  production: false,
  firebaseConfig: firebaseConfig,
  databaseName: 'development',
};

// From looking at the docs, the default databaseURL would be "https://firestore.googleapis.com/v1/projects/<projectId>/databases/(default)/"

我正在像这样导入我的

app.module

AngularFireModule.initializeApp(environment.firebaseConfig,),
AngularFirestoreModule

我也尝试过

AngularFireModule.initializeApp(environment.firebaseConfig, {name: environment.databaseName}),

AngularFireModule.initializeApp(environment.firebaseConfig, environment.databaseName),

如果我在网络浏览器中访问数据库URL,它会出现

缺少路由标头。请填写请求标头,格式为 x-goog-request-params:project_id=pocketmechanic-2970f&database_id=development。请参阅 https://firebase.google.com/docs/firestore/manage-databases#access_a_named_database_with_a_client_library 了解更多详情。

angular firebase google-cloud-firestore angularfire2
2个回答
2
投票

这是我的做法,请记住需要从兼容模式进行重构并使用模块化语法:


import { getApp, initializeApp, provideFirebaseApp } from "@angular/fire/app";
import { initializeFirestore, provideFirestore } from "@angular/fire/firestore";

@NgModule({
  imports: [
    provideFirebaseApp(() => initializeApp(config)),
    provideFirestore(() => {
      const app = getApp();
      const dbName = "db-name";
      const providedFirestore = initializeFirestore(app, {}, dbName);
      return providedFirestore;
    }),
  ]
})

然后在您的服务中:

import { inject } from "@angular/core";
import { Firestore, getDocs } from "@angular/fire/firestore";
import {
  collection,
  query,
  where,
  orderBy,
} from "@angular/fire/firestore";

@Injectable({
  providedIn: "root",
})
export class MyService {
  private firestore: Firestore = inject(Firestore);

  getUsers() {
    return getDocs(
      query(
        collection(this.firestore, "Users"),
        where("some_id", "==", "id"),
        orderBy("created_at", "asc")
      )
    );
  }
}

这还可以让您连接到多个数据库并根据需要注入它们。


0
投票

2025 年(直到球门柱再次改变),这对我有用:

    provideFirestore(() => {
      const firestore = getFirestore('your-database-name')
      if (environment.useEmulators) {
        connectFirestoreEmulator(firestore, 'localhost', 8080)
      }
      return firestore
    }

打开云 Firestore 时可在 url 中找到数据库名称

/project/<projectId>/firestore/databases/your-database-name/data
© www.soinside.com 2019 - 2024. All rights reserved.