检查用户是否存在于使用流量路由器的每条路由中
我在流星中有用户配置文件。检查用户是否存在于使用流量路由器的每条路由中
我正在使用流量路由器。
我想检查用户是否存在于每条路线上。
我已经试过
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 。
我想使用流路由器提供的notFound配置来存在不存在的路由。我想这也可以应用于'不存在的数据'。
因此,如果路由路径为/users/:userId
并且具有特定userId的用户不存在,则路由器应将该路由解释为无效路径。
FlowRouter documentation on auth logic and permissions建议控制哪些内容显示为未登录与登录用户在您的模板而不是路由器本身。铁路由器模式通常在路由器中进行认证。
对于您最近的问题您的具体问题:
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()
。
为什么我不能使用triggersEnter或这个?现在我正在检查用户是否登录或不在路由器中,但如果用户同时拥有墙,信息页,图库等(就像在Facebook上一样),我想要一些聪明的方法来检查在尝试检索有关此用户的数据之前,用户完全存在。 – Jamgreen
你要做的模板层上的检查,所以在主要布局在这里做的检查是好的指南:https://kadira.io/academy/meteor-routing-guide/content/介绍流程路由器 –
我已阅读指南,但我没有看到它提及如何在流路由器中使用notFound配置。我希望应用程序在访问配置文件路由时不存在用户不存在的模板。 – Jamgreen