【问题标题】:Meteor - How can I get server data from a URL parameter?Meteor - 如何从 URL 参数获取服务器数据?
【发布时间】:2016-06-05 20:25:32
【问题描述】:

我正在尝试根据 MeteorJS 中路由上的 URL 参数返回不同的数据。

在 nodejs 的背景下,我会这样做:

testPage = function (req, res, next) {
    //Got parameter query from url
    console.log('Getting at /testPage/:query '+req.params.query);

    //do something with that parameter, say make an HTTP call or query database
    var newThing = req.params.query+"hi";

    // render the page
    var data = {
        foo: newThing
    };
    res.render('testPage', data);
};

Meteor 不支持服务器端渲染,所以不支持。我还在纠结 Meteor 的单页客户端渲染;我应该如何在 Meteor 中解决这个问题?

我的第一次尝试(使用 IronRouter):

Router.route('/testPage/:query', function () {
    console.log("Got param at /testPage/:query "+this.params.query);
    if(Meteor.isServer){
        console.log("This code may never be called?");
        //Otherwise, make an HTTP call 
        //  and then somehow pass the data back to the client...
    }
    this.render("query");
});

这是我可以用反应变量做的事情吗?或者也许从客户端向单独的服务器端点进行 AJAX 调用?

【问题讨论】:

  • 我建议当路由改变时在客户端获取查询参数。然后使用新参数调用服务器方法。 Router.current() 是响应式的,因此您可以在自动运行中检查其参数,并将您的方法调用也放入其中。如果我有时间,我会尝试制作一个 Meteorpad 来演示。

标签: meteor client-server single-page-application iron-router


【解决方案1】:

iron-router 的规范模式是使用路由参数订阅数据:

Router.route('/foo/:bar',{ // Route takes a single parameter
  name: 'foo',
  waitOn: function(){
    return Meteor.subscribe('fooPublication', this.params.bar);
  }
});

在此示例中,this.params.bar 是路由的唯一参数。它作为参数传递给Meteor.subscribe。服务器可以使用该参数来决定将什么发布回客户端。 waitOn 保证模板渲染时数据在客户端可用。

【讨论】:

  • 对于其他不太了解订阅/发布的人,我将 Meteor.publish 放在我的基础服务器代码中,并在调用此订阅函数时调用它!正是我想要的
【解决方案2】:

您可以将 .render 方法上的数据作为第二个参数传递

Router.route('/testPage/:query', function () {
    console.log("Got param at /testPage/:query "+this.params.query);
    if(Meteor.isServer){
        console.log("This code may never be called?");
        //Otherwise, make an HTTP call 
        //  and then somehow pass the data back to the client...
    }
    this.render("query", {data: queryResult });
});

【讨论】:

    猜你喜欢
    • 2017-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-16
    • 2017-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多