在用户登录过程中显示加载程序

时间:2012-12-07 05:53:41

标签: meteor

我正在使用Accounts API来管理用户。我的应用首先尝试使用其凭据登录用户,如果导致错误,则会使用输入凭据创建新的用户帐户。

// Log the user in
Meteor.loginWithPassword(username, token, function(error) {
    if(error) { // create a new user account, log them in and show the page
        Accounts.createUser({
            username: username,
            email: username + '@example.com',
            password: token,
            profile: {name: username}
        }, showThePage);
    }
    else { // show the page
        //showThePage();
        window.location.reload();
    }
});

但此代码块仅在用户之前从浏览器中注销时执行,如果是这种情况,Meteor需要2-3秒才能使用loginWithPassword登录用户。由于我使用的是v0.5.0,因此没有Meteor.loggingIn(),我唯一拥有的是Meteor.userLoaded()。由于某种原因,Meteor执行两次登录操作 - 一次是通过加载占位符用户(仅设置了userId属性)再次加载实际用户。这使得userLoaded()返回true两次,因为我的加载器图像无法按预期工作。

另请注意,在loginWithPassword中的else块中,我正在重新加载窗口。我有一个函数showThePage(),其中包含所有模板数据&事件绑定代码。该函数使用登录用户的用户名检索数据。现在因为当else块中的那个函数执行时,没有真正的用户登录(记住meteor需要时间来记录用户),没有数据被提取。

此问题是否有解决方法?

2 个答案:

答案 0 :(得分:0)

首先,升级到0.5.0以后,Meteor.userLoaded会消失。你应该检查Meteor.userId()=== null是否知道用户登录是否已经完成,这在0.5.0及更高版本中有效。正如您所指出的那样,它可能被多次调用,但只有当它具有实际值时才会被登录完成。

答案 1 :(得分:0)

如果您确实无法更新到0.5.1,请使用会话变量在loggingIn的调用和回调之间存储loginWithPassword

Session.set('loggingIn',true);
Meteor.loginWithPassword(...
  Session.set('loggingIn',false);
});

然后,在适当的时候使用Session.get('loggingIn')电话。

想要改编userLoaded()吗?

var userLoadedTimes = 0; // can't use session variable because it would mess up reactive context on increments
Session.set('loggingIn',false);
Meteor.autorun(function () {
  var userLoaded = Meteor.userLoaded(); // reactive.
  if (userLoaded)
    userLoadedTimes++;
  if ((userLoadedTimes % 2 == 0) && (userLoadedTimes != 0))
    Session.set('loggingIn',true);
  else
    Session.set('loggingIn',false);
});

模数在那里做什么?好吧,如果userLoaded由于某种原因已经两次调用了被动上下文,那么您实际上已经登录了。所以我们检查userLoadedTimes是否是两个/偶数的倍数。所有其他时间,即当userLoadedTimes为奇数(userLoadedTimes % 2 == 1)时,我们正在查看虚假用户...这意味着我们仍在加载真实用户!

如果这不起作用,在Meteor调用loginWithPassword两次回调的情况下,使用回调上的会话变量更改将偶数/奇数逻辑应用于第一个解决方案。