【问题标题】:How to export Firestore when offline persistence is activated?激活离线持久性时如何导出 Firestore?
【发布时间】:2018-06-14 08:47:26
【问题描述】:

我一直在 ReactJS 框架中使用 Firebase。我已经设置了一个 config.js 来初始化 Firebase 并导出我的 firestore 实例,现在一切正常:

export const store = firebase.firestore();

我正在尝试启用离线持久性,但我现在应该如何导出我的 store 变量?

firebase.firestore().enablePersistence()
  .then(function() {
      // Initialize Cloud Firestore through firebase
      var store = firebase.firestore();
  })
  .catch(function(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
          // ...
      }
  });

我试图导出承诺,但它不起作用。有什么建议吗?

【问题讨论】:

    标签: javascript firebase google-cloud-firestore


    【解决方案1】:

    由于他们改变了行为并且没有告诉我们正确的方法,我这样做了:

    firestore.js:

    import firebase from 'firebase'
    import 'firebase/firestore'
    
    export var db = firebase.firestore()
    const settings = { timestampsInSnapshots: true }
    db.settings(settings)
    
    
    export function initializeDatabase() { 
        return new Promise((resolve, _) => {
            firebase.firestore().enablePersistence({experimentalTabSynchronization:true})
            .then(function() {
    
                //update the database variable to reflect the one with persistenceEnabled
                db = firebase.firestore();
    
                resolve()
              })
              .catch(function(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
                    // ...
                }
    
                //Nothing to do, it was previsoly initilaized in the var db 
                resolve()
              });
    })
    }
    

    现在在 main.js 中,你应该调用初始化数据库的方法

    main.js:

    let app;
    
    initializeDatabase().then(function() {
      initializeSecureApp()
    })
    
    function initializeSecureApp() {
      if(!app) {
        app = new Vue({
          router,
          store,
          render: h => h(App)
        }).$mount('#app');
    
        // defaultListeners()
      }
    }
    

    ps:我有点菜鸟,但这是我发现只有在设置持久性数据库后才启动应用程序的唯一方法

    ps:对不起,如果问题是旧的,但我今天遇到了这个问题,不得不搜索它

    ps:你可以实现reject而不是_并更新对initializeDatabase的调用来处理错误

    如果有人有更好的方法,请在这里发帖

    【讨论】:

      猜你喜欢
      • 2021-05-10
      • 2021-04-25
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 2021-10-27
      • 2017-01-08
      • 1970-01-01
      • 2018-05-24
      相关资源
      最近更新 更多