[英]Meteor Routing, Pub/Sub
我正在嘗試發表發表聲明,以僅發表author(OP)的個人資料頭像。 我正在考慮獲取頁面的_id
。 而從該頁面中,我將抓住userId
這是筆者的_id
,並嘗試以顯示個人資料。
但是,我一直做不到成功,目前,我正在使用以下內容。 發布每個用戶的個人資料頭像。
//Need to filter this to show only OP.
Meteor.publish("userPostAvatar", function() {
return Meteor.users.find( {} ,
{
fields: {'profile.avatar': 1}
})
});
Meteor.publish('singlePost', function(id) {
check(id, String);
return Posts.find(id);
});
Router.route('/posts/:_id', {
name: 'postPage',
waitOn: function() {
return [
Meteor.subscribe('singlePost', this.params._id),
Meteor.subscribe('userStatus'),
Meteor.subscribe('userPostAvatar')
];
},
data: function() {
return Posts.findOne({_id:this.params._id});
}
});
您可以在userPostAvatar
發布函數中進行如下簡單的連接:
Meteor.publish('userPostAvatar', function(postId) {
check(postId, String);
var post = Posts.findOne(postId);
return Meteor.users.find(post.authorId, {fields: {profile: 1}});
});
假定帖子具有authorId
字段-根據您的用例進行調整。 注意三件事:
您需要像使用singlePost
一樣訂閱this.params._id
。
聯接是非反應性的。 如果作者更改,該頭像將不會重新發布。 考慮到帖子的一般性質,我認為這不是問題。
我沒有故意發布嵌套字段profile.avatar
,因為這樣做會導致客戶端出現奇怪的行為。 有關更多詳細信息,請參見此問題 。
我相信您可以在iron:router數據上下文中實現此目的,方法是查找帖子,關聯的作者(無論該字段是什么),然后查找后續的用戶頭像。 您可以將對象返回到iron:router數據上下文。 然后,您可以訪問模板中的post
和avatar
作為變量(因此您可能需要稍微調整模板輸出)。
Publications.js
Meteor.publish("userPostAvatar", function() {
return Meteor.users.findOne( {} ,
{
fields: {'profile.avatar': 1}
})
});
Meteor.publish('singlePost', function(id) {
check(id, String);
return Posts.find(id);
});
Router.js
Router.route('/posts/:_id', {
name: 'postPage',
waitOn: function() {
return [
Meteor.subscribe('singlePost', this.params._id),
Meteor.subscribe('userStatus'),
Meteor.subscribe('userPostAvatar')
];
},
data: function() {
var post = Posts.findOne({_id: this.params._id});
var avatar = Users.findOne(post.authorId).profile.avatar;
return {
post: post,
avatar: avatar
};
}
});
這種方法的兩個問題是,您可以使用模板助手來實現相同的目的,並且用戶發布並不僅限於一個用戶(我不確定如何執行此操作,除非我們知道waitOn中的authorId,盡管也許您可以嘗試將邏輯移到那里而不是如我的示例所示的數據上下文)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.