Angular项目Firebase Firestore本地正常部署后报错:Service firestore is not available
本地运行Angular项目时,引入@angular/fire使用Firestore一切正常,可正常写入数据,但部署到Firebase Hosting后功能完全失效,且构建过程无任何错误。
部署后应用抛出如下错误:
core.mjs:6412 ERROR Error: Uncaught (in promise): Error: Service firestore is not available
Error: Service firestore is not available
使用的@angular/fire版本:
"@angular/fire": "^7.6.1",
环境文件配置
environment.ts
export const environment = { production: false, firebaseConfig: { apiKey: '***' authDomain: '***' projectId: '***' storageBucket:'***', messagingSenderId: '***', appId: '***', measurementId: '***' }, };
environment.prod.ts
export const environment = { production: true, ... (same as env.ts) };
Firebase初始化代码(app.module.ts)
import { initializeApp, provideFirebaseApp } from "@angular/fire/app"; import { provideFirestore, getFirestore } from "@angular/fire/firestore" @NgModule({ declarations: [AppComponent], imports: [ provideFirebaseApp(() => initializeApp(environment.firebaseConfig)), provideFirestore(() => getFirestore()) ], providers: [], bootstrap: [AppComponent], }) export class AppModule {}
服务中Firestore注入方式
import { Firestore } from "@angular/fire/firestore"; @Injectable({ providedIn: "root", }) export class FirebaseService { constructor(private firestore: Firestore) {...}
解决方法
检查Firestore服务状态
登录Firebase控制台,确认对应项目的Cloud Firestore已创建并启用,不是未初始化状态。修复环境文件语法错误
你的environment.ts中firebaseConfig的属性末尾缺少逗号,本地开发可能有容错,但生产构建会严格解析,修正后:export const environment = { production: false, firebaseConfig: { apiKey: '***', authDomain: '***', projectId: '***', storageBucket:'***', messagingSenderId: '***', appId: '***', measurementId: '***' }, };同步修正
environment.prod.ts的对应部分。核对生产环境Firebase配置
不要直接用...(same as env.ts)复制,手动确认environment.prod.ts里的firebaseConfig和Firebase控制台的项目配置完全一致,重点检查projectId和apiKey。升级@angular/fire版本
7.6.1版本可能存在部署兼容问题,升级到最新稳定版:npm install @angular/fire@latest检查Hosting重写规则
在firebase.json中确保重写规则正确,避免路由干扰Firestore初始化:{ "hosting": { "public": "dist/你的项目名", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ], "rewrites": [ { "source": "**", "destination": "/index.html" } ] } }清理缓存后重新构建部署
执行命令清理缓存、重新构建并部署:npm run build --prod --clean firebase deploy --only hosting
内容的提问来源于stack exchange,提问作者Ahmed

