【问题标题】:angular-meteor: notify client when new document insertedangular-meteor:插入新文档时通知客户端
【发布时间】:2015-01-12 07:14:40
【问题描述】:

我正在使用 angularjs 和流星实现一个通知系统。

在我的发布代码中,

我有这样的事情:

    var retVal = Notifications.find({recipient: userId});

var handle = retVal.observeChanges({
    //when a new notification is added
    added: function (doc, idx) {
        count++;
        if (!initializing){
            console.log("A record was added");
            self.changed("counts", userId, {count: count});
        }
    },

    removed: function (doc, idx) {
        count--;
        self.changed("counts", userId, {count: count});    
    }

});

最后我返回了 retVal。 在我的控制器中,我订阅了该出版物。 代码看起来很好,每当添加新文档时服务器都会触发添加的功能。但是,当添加新文档时,如何通知客户端(例如在我的控制器中触发一个函数)?添加的功能只在服务器触发。

【问题讨论】:

    标签: angularjs meteor


    【解决方案1】:

    我看不到您的发布标题,您希望那里有参数吗?

    要绑定集合,您只需使用 $meteorCollection 服务,如下所示:

    $scope.notifications = $meteorCollection(Notifications);
    

    我们刚刚更新了我们的 API(版本 0.6.0-alpha),它会在内部观察更改以查找集合中的任何更改。

    但不要忘记订阅该收藏 - 您可以通过 2 种方式进行订阅:

    1. $meteorSubscribe.subscribe("publicationName", parameters) - 返回一个承诺。
    2. $scope.notifications = $meteorCollection(Notification).subscribe("publicationName", parameters); - 更短但不返回承诺。

    如果其中一个参数改变了发布,你应该像这样用 autorun 包围它:

    $meteorUtils.autorun($scope, function(){
      $meteorSubscribe.subscribe("publicationName", {
            limit: parseInt($scope.getReactively('perPage')),
            skip: (parseInt($scope.getReactively('page')) - 1) * parseInt($scope.getReactively('perPage')),
            sort: $scope.getReactively('sort')
          }));
    });
    
    • $scope.getReactively 是我们添加的一种新方法,它使常规的 $scope 变量变为响应式变量。这意味着当它发生变化时,自动运行将重新运行。

    希望对您有所帮助,让我知道如何改进答案和文档。

    【讨论】:

      【解决方案2】:

      我认为您应该在客户端上复制您的observeChanges()。 因此,它将能够观察由subscribe() 函数创建和同步的客户端集合。

      【讨论】:

      • 我如何用 angularjs 做到这一点?我使用服务 $collection 和 $methods。我搜索了 observeChanges 方法,但找不到这样的方法。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-25
      • 1970-01-01
      • 2016-10-25
      • 2014-01-16
      • 2015-08-15
      • 2015-07-03
      • 1970-01-01
      相关资源
      最近更新 更多