2015-11-06 35 views
0

我在流星中有用戶配置文件。檢查用戶是否存在於使用流量路由器的每條路由中

我正在使用流量路由器。

我想檢查用戶是否存在於每條路線上。

我已經試過

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的用戶不存在,則路由器應將該路由解釋爲無效路徑。

+0

你要做的模板層上的檢查,所以在主要佈局在這裏做的檢查是好的指南:https://kadira.io/academy/meteor-routing-guide/content/介紹流程路由器 –

+0

我已閱讀指南,但我沒有看到它提及如何在流路由器中使用notFound配置。我希望應用程序在訪問配置文件路由時不存在用戶不存在的模板。 – Jamgreen

回答

1

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()

docs

+0

爲什麼我不能使用triggersEnter或這個?現在我正在檢查用戶是否登錄或不在路由器中,但如果用戶同時擁有牆,信息頁,圖庫等(就像在Facebook上一樣),我想要一些聰明的方法來檢查在嘗試檢索有關此用戶的數據之前,用戶完全存在。 – Jamgreen