【问题标题】:Angular JS filters using Firebase data使用 Firebase 数据的 Angular JS 过滤器
【发布时间】:2014-08-13 11:09:18
【问题描述】:

我在 firebase 中有一些如下所示的数据:

|
|
--users
    |
    --1
      |
      --email:"hello@gmail.com"
      --name:"User 01"
    --2
      |
      --email:"hello2@gmail.com"
      --name:"User 02"
--chat
    |
    ---JU9ZpBj7P9dWgNYN4To
      |
      --email:"hello@gmail.com"
      --content:"Hi, i'm user 01! How are you?"
      --user:"1"
      --timestamp:"123456789"
    ---JX8ZpBnli7hliwehlfi
      |
      --email:"hello2@gmail.com"
      --content:"Hi, i'm user 02! I'm great thanks!"
      --user:"2"
      --timestamp:"123456789"

我在一个名为“消息”的对象中从 firebase 获取聊天数据,我的 HTML/angular 看起来像这样:

<ul class="chat" ng-repeat="message in messages  | orderByPriority | reverse">
    <li>
        <strong>{{message.user | uid2name}}</strong> {{message.content}}
    </li>
</ul>

所以我想做的是获取 message.user 并将其从用户 ID 转换为名称。我想一个好方法是使用过滤器:

.filter('uid2name', function(loginService, $rootScope) {

// Takes a userid and outputs a users name
return function(input) {
      var ref = new Firebase('https://<myapp>.firebaseio.com/users/' + input);
      return $firebase(ref).name;
};
})

现在这很好用,但它实际上是通过每秒多次轮询 firebase 来实现的——这根本不是我想要做的。我曾考虑在 $rootScope 中缓存响应,但这似乎有点草率。最好的方法是什么?我对任何想法持开放态度,我不喜欢使用过滤器的想法。

【问题讨论】:

    标签: angularjs firebase angularfire


    【解决方案1】:

    过滤器是我最喜欢 Angular 的东西之一,但是它们太重了(因为它们在每个摘要循环中都会被评估)并且绝对不适合你的方法,除非你使用缓存(只是不要存储它在 $rootScope 中,创建一个缓存服务)。

    Firebase 只关乎性能,在大多数情况下,标准化是您的敌人。您已经存储了用户电子邮件,为什么不也存储用户名呢?

    更改数据结构以在 Chat 数据结构的 URL 中包含 userId 可能会有所帮助:Data Modeling Best Practices in Firebase/AngularFire

    【讨论】:

    • 如果我将用户名存储在每个聊天条目中,当他们使用更改名称时会发生什么?我希望能够使用名称更改或其他信息来更新以前的聊天条目。不过我会检查创建缓存服务....谢谢:)
    • @NathanMoynihan 另一种方法是改变你的数据结构,也许这个答案可以帮助你:stackoverflow.com/questions/25223690/…
    【解决方案2】:

    最后,我通过使用angular-cache 插件解决了这个问题(默认的角度缓存工厂很好,但它缺少一些有用的功能)。我缓存了用户,以便在不影响 firebase 的情况下使用过滤器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-12
      相关资源
      最近更新 更多