简体   繁体   English

如何等待Meteor.user()在Template onRendered中定义

[英]How to wait for Meteor.user() to be defined in Template onRendered

I am working on a Meteor project and I need to access some information stored in a user's profile to make a map on the page. 我正在研究Meteor项目,我需要访问存储在用户个人资料中的一些信息才能在页面上绘制地图。 However, when I try to access Meteor.user(), I receive undefined because when the function is called, Meteor.user() has not been loaded. 但是,当我尝试访问Meteor.user()时,收到未定义的信息,因为调用该函数时,尚未加载Meteor.user()。

Template.body.onRendered () ->
    console.log Meteor.user()
    address = Meteor.user()['profile']['address']

    GoogleMaps.ready 'studyMap', (map) ->
        # maps code that relies on address

Because Meteor.user() is not defined, I am not able to get the map to work. 由于未定义Meteor.user(),因此无法使地图正常工作。 How can I wait for Meteor.user() to be defined? 如何等待Meteor.user()定义?

I think your going to need an asynchronous callback to load the map only when address = Meteor.user()['profile']['address'] loads. 我认为您仅在address = Meteor.user()['profile']['address']加载时才需要异步回调来加载地图。 As far as how to implement this, I'm not really sure. 至于如何实现这一点,我不确定。

One of my apps has to do something similar to wait on a subscription. 我的一个应用程序必须执行类似操作才能等待订阅。 I defined the waitOn() handler in my router. 我在路由器中定义了waitOn()处理函数。

Router.map(function(){
  this.route('Brocator', {
    path: '/',
    template: 'brocator',
    waitOn: function() {
      return (Meteor.subscribe('people', this.params._gridId)
        && Meteor.subscribe('gridlog', this.params._gridId) );
    },
    data: function() {
      var gridId = this.params._gridId;
      return (People.find({gridId: gridId})
        && GridLog.find({gridId: gridId}));
    },
    fastRender: true
  }),
  ... other routes deleted for clarity
})

You may decide to use something along the lines of 您可能决定按照以下方式使用某些东西:

return Meteor.user() != 'undefined';

in your waitOn() handler. 在您的waitOn()处理函数中。

Posted an answer for meteor/react here however the same can be done with blaze. 在这里发布流星/反应的答案,但是同样可以大放异彩。 I am not familiar with blaze but within your Template.body.onRendered function you can listen to make sure that the login services are configured before rendering anything. 我对火焰并不熟悉,但是在Template.body.onRendered函数中,您可以侦听以确保在呈现任何内容之前已配置登录服务。

Tracker.autorun(() => {
  if (Accounts.loginServicesConfigured()) {
    // accounts is ready go ahead and render
  } else {
    // still waiting show loading spinner
  }
});

I would recommend extracting this logic out to a higher level so that you don't keep repeating the same code. 我建议将此逻辑提取到更高的级别,以免您重复执行相同的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM