【问题标题】:Meteor how can I delay rendering template by 3 seconds流星如何将渲染模板延迟 3 秒
【发布时间】:2015-07-03 17:02:58
【问题描述】:

我有一个登录表单模板

<template name="loginPage">...content</template>

并且在{{currentUser}} 未登录时呈现。 问题是currentUser在页面刷新后大约一秒钟内不可用,即使用户登录也是如此。这导致登录页面出现一秒钟,即使用户已经登录,这看起来也不好.知道如何延迟呈现登录页面,以确保{{currentUser}} 是否真的登录?

[已解决]

html

{{#if loggingIn}}
  please wait, user is logging in
{{/if}}
{{#unless loggingIn}}
  {{#if currentUser}}
    user logged in
  {{/if}}
  {{#unless currentUser}}
    login form
  {{/unless}}
{{/unless}}

js

// create global {{#if loggingIn}}{{/if}} helper
Session.set("loggingIn", true);
var loginWait = 3; // seconds
var loginTimeout = setInterval(function(){
  loginWait = loginWait - 1;
  if(loginWait <= 0 || Meteor.user()){
    Session.set("loggingIn", false);
    clearInterval(loginTimeout);
  }
},1000);
Handlebars.registerHelper('loggingIn', function () {
  return Session.get("loggingIn");
});

【问题讨论】:

  • 使用路由来实现这一点,以及路由器挂钩 (onBeforeAction)。所以路由器会检查用户是否登录,如果没有登录,你执行this.redirect() 去另一个路由,或者this.render() 渲染一个模板。见:iron-meteor.github.io/iron-router/#using-redirects

标签: javascript meteor meteor-blaze meteor-accounts


【解决方案1】:

在您的模板中,您可以执行以下操作:

{{#if loggingIn}}
  HTML to be rendered before the user is determined
{{else}}
  {{#if currentUser}}  
    Html to be rendered if the user is logged in 
  {{else}}  
    Html to be rendered if the user is not logged in
  {{/if}}
{{/if}}

顺便说一句,我确实意识到这并不能提供您要求的答案,但我认为这可能是一个更好的方法。

【讨论】:

  • 没关系,我在问之前找到了相同的解决方案。我已经用解决方案更新了我的问题,部分基于您的建议:)
【解决方案2】:

进行用户登录检查的正确位置是在 JS 的 onRendered 方法中。

Template.loginPage.onRendered(function () {
  if(! Meteor.user()) {
    //route somewhere else
  }
});

你不需要添加一个不确定的加载时间,onRendered会在模板渲染之前被调用,所以你不用担心你分配的时间是否足够。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-16
    • 1970-01-01
    • 2012-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多