Meteor.userId() 登录后在 Iron Router 路由中未定义

Meteor.userId() undefined in Iron Router Route After Logging In

当用户首次加载站点而不登录,然后登录时,下面定义的路由 account 将解析为 /profile/null。在路由路径变为正确之前,用户必须刷新站点。

this.route('account', {
    template: 'profile',
    path: '/profile/' + Meteor.userId()
})

之所以专门创建一个路由来接受参数Meteor.userId()是因为我使用的package需要我定义path名称,即:{{> ionTab title="Account" path="account"}} 我认为它不能带参数。

改进这条路线的更好方法是什么?

路由定义在您的应用程序启动时发生一次,此时 Meteor.userId() 仍未定义,因此这就是您的代码无法正常工作的原因,但整个方法是错误的,您应该将您的路由定义为关注 :

Router.route("/profile/:_id",{
  name:"profile",
  template:"profile",
  waitOn:function(){
    return Meteor.subscribe("userProfile",this.params._id);
  },
  data:function(){
    var user=Meteor.users.findOne(this.params._id);
    return {
      user:user
    };
  }
});

您在 iron:router 文档中可能错过的是定义采用参数(/path/:param 语法)的路由并使用此参数配置路由订阅和数据上下文的可能性。

编辑

如果想获取此路由对应的动态路径,可以使用path方法:

HTML

<template name="myTemplate">
  {{> ionTab title="Account" path=accountPath}}
</template>

JS

Template.myTemplate.helpers({
  accountPath:function(){
    return Router.path("profile",Meteor.user());
  }
});