使用Flow Router检查每个路由中是否存在用户



我在Meteor中有一个用户配置文件。

我正在使用Flow Router。

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

我试过

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;
  },
} );

但它只会用变量CCD_ 1填充模板,该变量要么是用户对象要么是null。

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

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

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

对于您最近问题中的特定问题:

html:

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

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

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

注意,即使Meteor.user()还没有被加载,Meteor.userId()也存在。

文档

最新更新