首页 > 解决方案 > 如何在 Angular 中实现 Firebase 分布式计数器扩展

问题描述

我正在尝试在我的 Angular 应用程序中实现Firebase 分布式计数器扩展,但我不太确定如何去做。说明说要将sharded-counter.js文件包含在您的项目中,他们给出了以下示例:

<html>
 <head>
  <script src="https://www.gstatic.com/firebasejs/[version]/firebase-app.js"></script>
  <script src="https://www.gstatic.com/firebasejs/[version]/firebase-firestore.js"></script>
  <script src="sharded-counter.js"></script>
</head>
<body>
 <script>
  // Initialize Firebase.
  var firebaseConfig = { projectId: "at-the-dinner-table" };
  firebase.initializeApp(firebaseConfig);
  var db = firebase.firestore();

  // Initialize the sharded counter.
  var visits = new sharded.Counter(db.doc("pages/hello-world"), "visits");

  // Increment the field "visits" of the document "pages/hello-world".
  visits.incrementBy(1);

  // Listen to locally consistent values.
  visits.onSnapshot((snap) => {
    console.log("Locally consistent view of visits: " + snap.data());
  });

  // Alternatively, if you don't mind counter delays, you can listen to the document directly.
  db.doc("pages/hello-world").onSnapshot((snap) => {
    console.log("Eventually consistent view of visits: " + snap.get("visits"));
  });
 </script>
 </body>
</html>

我曾尝试使用导入此文件,import * as sharded from 'file path'但随后我收到Counter不是构造函数的消息。我确定我缺少一些东西,所以任何帮助将不胜感激!

标签: angulartypescriptfirebasegoogle-cloud-firestorefirebase-extensions

解决方案


我最终改用了Typescript 文件。在我实现分片计数器的文件中,我导入了 TS 文件,import * as sharded from 'file path'我必须在 TS 文件中导入 Firebase。之后,一切都按预期进行。

我仍然想知道为什么最小化的 JS 文件没有以同样的方式工作,但我很高兴现在一切正常!


推荐阅读