0

我在 Meteor 中有一个用户个人资料。

我正在使用流路由器。

我想检查用户是否存在于每条路线上。

我努力了

const userRedirect = ( context, redirect, stop ) => {
  let userId = FlowRouter.getParam( 'userId' );

  if ( Meteor.users.find( { _id: userId } ).count() === 0 ) {
   FlowRouter.go( 'userList' );
  }
};

const projectRoutes = FlowRouter.group( {
  name: 'user',
  triggersEnter: [ userRedirect ]
} );

userRoutes.route( '/users/:userId', {
  name: 'userDetail',
  action: function ( params, queryParams ) {
    BlazeLayout.render( 'default', { yield: 'userDetail' } );
  },
} );

但它不起作用。

我猜是因为我还没有订阅用户收藏。

我怎样才能在路线中做到这一点?我应该使用

const userRedirect = ( context, redirect, stop ) => {
  let userId = FlowRouter.getParam( 'userId' );

  // subscribe to user
  Template.instance().subscribe( 'singleUser', userId );

  // check if found
  if ( Meteor.users.find( { _id: userId } ).count() === 0 ) {
   FlowRouter.go( 'userList' );
  }
};

编辑

我尝试使用模板签入

Template.userDetail.onCreated( () => {
  var userId = FlowRouter.getParam( 'userId' );
  Template.instance().subscribe( 'singleUser', userId );
});

Template.userDetail.helpers( {
  user: function () {
    var userId = FlowRouter.getParam( 'userId' );
    var user = userId ? Meteor.users.findOne( userId ) : null;
    return user;
  },
} );

但它只会user使用用户对象或 null 的变量填充模板。

我想将 Flow Router 提供的 notFound 配置用于不存在的路由。我想这也可以应用于“不存在的数据”。

因此,如果路由路径是/users/:userId且具有特定 userId 的用户不存在,则路由器应将该路由解释为无效路径。

4

1 回答 1

1

FlowRouter 关于身份验证逻辑和权限的文档建议控制在模板中向未登录用户和登录用户显示哪些内容,而不是路由器本身。Iron-router 模式通常在路由器中进行身份验证。

对于您最近的问题中的具体问题:

html:

{{#if currentUser}}
  {{> yield}}
{{else}}
  {{> notFoundTemplate}}
{{/if}}

要使用触发器重定向,请尝试以下方式:

FlowRouter.route('/profile', {
  triggersEnter: [function(context, redirect) {
    if ( !Meteor.userId() ) redirect('/some-other-path');
  }]
});

请注意,Meteor.userId()即使Meteor.user()尚未加载,它也存在。

文档

于 2015-11-07T00:03:37.480 回答