如果数据库变量已更改Meteor,则重新加载页面内容

时间:2019-01-21 10:01:07

标签: node.js meteor meteor-blaze blaze

我正在开发流星应用程序。我想在数据库变量更改后重新加载客户端的内容。我正在使用pub-sub。如果状态变量已更改,我想加载内容。

Meteor.publish('activities', function(loggedInUserToken) {
    var authObj = AuthenticationToken.findOne({ authToken: loggedInUserToken });
    if (authObj) {
        var userObj = Users.findOne({ _id: authObj.user_id });
        var activities = Activities.find({}, { sort: { createdAt: -1 } });
        return activities;
    }
    return this.ready();
});


Template.masterSku.onCreated(function() {
    var instance = this;
    instance.autorun(function() {
        var loggedInUserToken = "xxxxxxxxxxxxxxxx"
        statusSuscription = instance.subscribe("activities", loggedInUserToken);
        var activitiesObj = Activities.findOne({}, { sort: { createdAt: -1 } })
        if (activitiesObj && activitiesObj.status == "true") {
            console.log("Status Changed load Content accordingly")
        }
})

2 个答案:

答案 0 :(得分:0)

autorun不会重新计算,除非反应性数据已更改并且在计算中请求此更改。虽然订阅是被动来源,但您还需要检查订阅是否就绪,从而导致新的计算周期:

instance.autorun(function() {
    var loggedInUserToken = "xxxxxxxxxxxxxxxx"
    var statusSuscription = instance.subscribe("activities", loggedInUserToken);
    if (statusSuscription.ready()) { // causes a new compuation by the Tracker
      var activitiesObj = Activities.findOne({}, { sort: { createdAt: -1 } })
      if (activitiesObj && activitiesObj.status == "true") {
        console.log("Status Changed load Content accordingly")
        // here you can insert data into a ReactiveVar or ReactiveDict and use
        // result in a Template helper, which itself will cause your Template to re-render
      }
    }
}

答案 1 :(得分:0)

您可以在onCreated函数中使用Tracker,也可以尝试通过帮助器填充数据。

import { Tracker } from 'meteor/tracker';

Tracker.autorun(() => {
 var loggedInUserToken = "xxxxxxxxxxxxxxxx"
        statusSuscription = instance.subscribe("activities", loggedInUserToken);
        var activitiesObj = Activities.findOne({}, { sort: { createdAt: -1 } })
        if (activitiesObj && activitiesObj.status == "true") {
            console.log("Status Changed load Content accordingly")
        }
});