如何在激活脱机持久性时导出Firestore?

时间:2018-06-14 08:47:26

标签: javascript firebase google-cloud-firestore

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

export const store = firebase.firestore();

我尝试启用离线持久性但是现在应该如何导出我的商店变量?

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
          // ...
      }
  });

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

1 个答案:

答案 0 :(得分:0)

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

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:您可以实现拒绝而不是_并更新对initializeDatabase的调用以处理错误

如果有人有更好的方法,请在此处发布