首页 > 解决方案 > 启用离线持久性 Cloud Firestore

问题描述

我想使用 Cloud Firestore Javascript SDK 启用离线持久性。我已经构建了我的应用程序,例如由于 SSR 将 Firestore 存储为属性。

import firebase from "firebase/app";

export class GetFirebase {
private firestore: firebase.firestore.Firestore;
private firebaseApp: firebase.app.App;
private firebaseConfig = {} // has the config from firebase

 private constructor() {
  this.firebaseApp = firebase.initializeApp(this.firebaseConfig);
  this.firestore = firebase.firestore();
 }
}

如果我尝试使用该enablePersistence()方法,我将获得无效。

  this.firestore = firebase.firestore().enablePersistence();

我也不能这样做

  this.firestore = firebase.firestore();
  this.firestore.enablePersistence() // error cannot change settings after firestore is initialized.

我正在寻找与Dart..中的级联运算符等效的 Typescript 或 Javascript,但找不到它。

标签: javascripttypescriptfirebasegoogle-cloud-firestore

解决方案


导致持久性调用返回 void 的原因有很多:

  1. 与离线数据不兼容的版本,此功能未实现某些服务,例如 Node.js 我复制了您的案例,我发现它与 Node.js 不兼容,所以它是重要的是验证您的服务器firebase是否兼容离线启用。如果您打开多个选项卡也可能导致错误,一次只能在一个选项卡中启用持久性。当前浏览器不支持启用持久性所需的所有资源。对于 Web,仅 Chrome、Safari 和 Firefox Web 浏览器支持脱机持久性。

  2. 您正在进行异步调用,发生这种情况是因为您正在做出承诺,因此第一次打印值结果是无效的,因为响应尚未到达。但是,当 promise 收到信息时,它将不再是无效的。要了解有关如何工作的更多信息,请参阅Promise 文档

  3. 您没有处理承诺,这可能会导致问题。我做了一个复制,它引起了以下警告: UnhandledPromiseRejectionWarning: Unhandled Promise Rejection。此错误源于在没有 catch 块的情况下抛出异步函数内部,或拒绝未使用 .catch() firebase enable offline处理的承诺。


    firebase.firestore().enablePersistence()
      .catch((err) => {
          if (err.code == 'failed-precondition') {
              // Multiple tabs open, persistence can only be enabled
              // in one tab at a a time.
              // ...
          } else if (err.code == 'unimplemented') {
              // The current browser does not support all of the
              // features required to enable persistence
              // ...
          }
      });
    // Subsequent queries will use persistence, if it was enabled successfully

  1. 您正在使用服务器端渲染,因此可能会导致错误修复,您必须使用 process.browser 作为示例进程浏览器。我将此功能与 nextjs、node 和 vue 一起使用,并且可以正常工作。
    if (process.browser) {
      console.log('this code will only run on the browser')
    }

Cascade Operator 我建议你打开另一个线程来检查这个案例,因为它是另一个主题,以便更多人可以找到它。但是,我找到了一个博客,其中解释了如何将级联运算符转换为 JavaScript 。没有等价物,但有办法做到这一点。


推荐阅读