簡體   English   中英

使用流星調用和流星方法時的MeteorJS無限循環

[英]MeteorJS Infinite loop when using meteor call and meteor method

我有一個示例代碼,如下所示:

客戶幫手:

getUsername: function (userId) {
  Meteor.call("getUsername", userId, function (err, result) {
    if(!err) {
      Session.set("setUsername", result);
    else {
      console.log(err);
    }
  });
  return Session.get("setUsername");
}

服務器

Meteor.methods({
   "getUsername": function (userId) {
      var x = Meteor.users.find({_id: userId}, {fields: {username:1}}).fetch()[0];
      return x.username;
   }
});

此代碼的結果是傳遞給客戶端的用戶名無限循環。 有沒有一種方法可以停止循環並僅傳遞客戶端上所需的數據? 我相信反應性導致數據無限循環,我不確定如何停止它。 我嘗試在服務器中的查詢上使用"reactive":false ,但它不起作用。

如果要在客戶端模板中的任何地方訪問用戶名(這就是為什么要將其放入會話中),則不會在模板幫助器中進行設置。 我會在啟動時進行設置,並從模板助手中的會話中獲取用戶名(無需調用服務器方法)

如果僅在一個模板中需要用戶名,那么您想從模板助手中返回其值,請勿將其放入會話中,只需在服務器方法回調中返回即可。

我假設基於示例代碼,您擁有一組帖子,並且您正在根據每個帖子的用戶ID檢索用戶名。 然后,您應該使用publish復合包來發布相關用戶,而不是這樣做。

Meteor.publishComposite('getPosts', function (postIds) {
    return [{
        find: function() {
            return Posts.find({ _id: { $in: postIds }});
            // you can also do -> return Posts.find();
            // or -> return Posts.find({ /* or what ever your selector is to get the posts you need*/ });
        },
        children: [{
            find: function(post) {
                return Meteor.users.find({ 
                    id: post.userId //or the correct field in your post document to get user id 
                }, { 
                   fields: { 
                        "profile": 1
                   } 
                });
            }
        }}
    }]
});

這樣,您的出版物將負責發布相關用戶以及帖子。 您不需要每次都使用方法並調用它們。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM