简体   繁体   中英

How can I prevent Meteor.user()'s timing hole?

A template requests...

if (this.userRequesting._id === Meteor.user()._id) { ... }

...to check for a person's identity. (I suspect this isn't the best way to handle this, but I'll save that for another question so as to not overload this question).

My issue is that this results in a tremendous error cascade suggesting that Meteor.user() is undefined, only on pageload... Once the page is loaded, this code executes without a problem. Clearly, there is a timing hole (or so I believe) where Meteor.user() remains unassigned for a split second on page load. Replacing the above code with...

    ____________
if (Meteor.user() && this.userRequesting._id == Meteor.user()._id) { ... }

...fixes the problem, but... Come on ... That can't possibly be kosher. What assumption am I erroneously making about templating and Meteor?

If relevant, I'm using accounts-password as my cheat-y accounts manager.


[Edit]: This looks like the same problem , but I'm leaving this question up on the premise that I'm looking for a fix, not a workaround. (I already know checking for Meteor.user() resolves this.)

Yep, you've basically gotten it right. When you first refresh the page, the user isn't consider to be logged in, and it has to verify that it is. But the template stuff is called immediately, and then again when other stuff is loaded (if you put an alert in a rendered method, you'll notice that). The best solution is exactly what you suggested, although you can use Meteor.userId() to get just the id:

if (Meteor.userId() && Meteor.userId() === this.userRequesting._id) {
    // ...

您可以使用Meteor.userId()来获取已登录用户的_id属性,如果未登录,则为null (我认为)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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