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

Angular中Cloud Firestore连接失败,experimentalForceLongPolling配置是否正确?

问题解答

仅在environment.prod.ts中添加experimentalForceLongPolling字段是不完整的,必须确保该配置被正确传入Firestore的初始化逻辑,否则设置不会生效。

正确配置步骤(AngularFire 兼容版,即@angular/fire/compat)

  1. 完善environment.prod.ts配置
    在Firebase配置外单独定义Firestore设置,或直接嵌入到Firebase配置对象中:

    export const environment = {
      production: true,
      firebase: {
        apiKey: "你的API_KEY",
        authDomain: "你的AUTH_DOMAIN",
        projectId: "你的PROJECT_ID",
        storageBucket: "你的STORAGE_BUCKET",
        messagingSenderId: "你的SENDER_ID",
        appId: "你的APP_ID"
      },
      firestoreSettings: {
        experimentalForceLongPolling: true
      }
    };
    
  2. 在app.module.ts中传入配置
    初始化AngularFireModule后,通过AngularFirestoreModule.settings()方法将设置传入:

    import { NgModule } from '@angular/core';
    import { BrowserModule } from '@angular/platform-browser';
    import { AngularFireModule } from '@angular/fire/compat';
    import { AngularFirestoreModule } from '@angular/fire/compat/firestore';
    import { environment } from '../environments/environment';
    
    @NgModule({
      imports: [
        BrowserModule,
        AngularFireModule.initializeApp(environment.firebase),
        AngularFirestoreModule.enablePersistence(), // 可选:启用离线持久化
        AngularFirestoreModule.settings(environment.firestoreSettings)
      ],
      declarations: [/* 你的组件列表 */],
      bootstrap: [/* 根组件 */]
    })
    export class AppModule { }
    

若使用AngularFire v9+ 模块化版本

如果项目采用v9及以上的模块化API,配置方式略有不同:

  1. environment.prod.ts配置保持不变
  2. 初始化Firestore时传入设置
    import { initializeApp } from 'firebase/app';
    import { initializeFirestore } from 'firebase/firestore';
    import { environment } from '../environments/environment';
    
    const app = initializeApp(environment.firebase);
    // 初始化Firestore时直接传入配置
    const db = initializeFirestore(app, environment.firestoreSettings);
    

补充说明

experimentalForceLongPolling的作用是强制Firestore使用HTTP长轮询代替默认的WebSocket连接,可解决部分客户端网络环境(如企业内网、受限网络)中WebSocket被拦截导致的连接失败问题——本地开发环境通常无此类网络限制,因此不会触发错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 21:02:10