簡體   English   中英

如何在流星的助手中返回流星調用值

[英]how to return meteor call value in helper in meteor

我已經從HTML將ID傳遞給了助手,而我的助手是getusername

getusername(id) {
    var username = "";
    Meteor.call("getUserName", id, function(error, result) {
        if (error) {
            console.log("error", error);
        }
        if (result) {
            console.log(result);
            username = result;
        }
    });
    return username;
}

雖然我將結果記錄在日志中,但是我在UI中看不到用戶名。 當我將其與Reactive var一起使用時,它會變成無窮大...因為當無功變量值更改時,它會再次執行...

您不能異步獲取數據並從同一個幫助程序返回數據,因為該幫助程序在調用完成之前返回,並且沒有反應性變量表明一旦調用完成,數據已更改。 使用ReactiveVar是正確的,但是要避免無限循環,必須在模板幫助Meteor.call外部運行Meteor.call 我建議在模板的onCreated掛鈎中執行此操作:

Template.x.onCreated(function() {
  var self = this;
  Meteor.call("getUserName", this.data.id, function(error, result) {
    if (result) {
        self.username = new ReactiveVar(result);
    }
  });
});

Template.x.helpers({
  getUserName(id) {
    return Template.instance().username.get();
  }
});

但是請注意,在幾乎所有情況下,最好執行諸如直接在前端獲取用戶名之類的操作,例如return Meteor.users.findOne(id).profile.name ,因為這是反應性的,並且更加容易。

由於異步行為,您將無法獲得返回值。可以在會話中設置返回值,然后從任何需要的會話中獲取返回值

getusername(id) {
    var username = "";
    Meteor.call("getUserName", id, function(error, result) {
        if (error) {
            console.log("error", error);
        }
        if (result) {
            console.log(result);
            username = result;
        }
    });
    Session.set('getUserNameResult', result);
}

暫無
暫無

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

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