簡體   English   中英

在Meteor中沒有Collection.find的反應式更新

[英]No Reactive Update with Collection.find in Meteor

在具有FruitsMeteor.users集合的測試應用中,用戶使用服務器端代碼單擊水果的名稱以將其添加到他最喜歡的列表中

Meteor.users.update( Meteor.user()._id, { $push: {'profile.favorites': fruit_id } })

其中fruit_id是Mongo生成的ObjectID fruit._id

對於最喜歡的水果頁面,客戶端還訂閱出版物:

Meteor.publish('favoriteFruits', function() {

    return Fruits.find({
        '_id': {
            '$in' : Meteor.users.findOne(this.userId).profile.favorites
        }
    })

}

問題:將新水果設為收藏夾時,除非刷新頁面,否則收藏夾水果頁面上的任何內容都不會更改。

我的猜測是因為在發布代碼中,包含$in的行不是反應性的。

對於這種情況,通常的做法是使用戶能夠看到新添加或刪除的水果嗎? Meteor.users.findOne(this.userId).profile.favorites可以設為反應式嗎?


訂閱是在控制器中完成的,我在Angular和Meteor中使用。

angular.module('myApp').controller('FavoriteFruitsCtrl', function($scope, $meteor) {

    $meteor.autorun($scope, function() {

        $meteor
            .subscribe('favoriteFruits')
            .then(function() {
                $scope.favfruits = $meteor.collection(Fruits, false)
            })

    })

})

根據@SylvainB和@Billybobbonnet的建議,我們是否要這樣做? 每當Meteor.user().profile.favorites發生更改時,包含.subscribe的第二個自動運行都會重新運行!

angular.module('myApp').controller('FavoriteFruitsCtrl', function($scope, $meteor) {

    $meteor.autorun($scope, function() {
        Session.set('favorites', Meteor.user().profile.favorites)
    })

    // This autorun block will be triggered when the above autorun is triggered
    $meteor.autorun($scope, function() {
        var justForTriggering = Session.get('favorites')
        $meteor
            .subscribe('favoriteFruits')
            .then(function() {
                $scope.favfruits = $meteor.collection(Fruits, false)
            })
    })

})

但是,不會觸發$meteor.subscribe函數(通過在服務器端進行檢查)

我將使用喜歡的水果數組作為參數來創建模板級別的訂閱 它假定您在另一個出版物中公開了profile.favorite字段,但是默認情況下,當前用戶應該已經公開了它。

由於您會將訂閱包裝在自動運行中,並使用用戶集合中的光標,因此事件的原因如下:更新配置文件>觸發自動運行>更新喜歡的水果的發布。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM