【问题标题】:firebase simple authentication authClient is null?firebase 简单身份验证 authClient 为空?
【发布时间】:2013-05-28 09:30:56
【问题描述】:

下面是我正在玩的示例代码:

var myRootRef = new Firebase('https://url.firebaseIO.com/');

var authClient = new FirebaseAuthClient(myRootRef, function(error, user) {
    if (error) {
        // an error occurred while attempting login
        console.log(error);
    } else if (user) {
        // user authenticated with Firebase
        console.log('User ID: ' + user.id + ', Provider: ' + user.provider);
    } else {
        // user is logged out

        console.log('logged out!');
        login();
    }
});


function login(){
    var email = "something@gmail.com";
    var password = "123";

    authClient.login('password', {
        email: email,
        password: password,
        rememberMe: true
    });
}

我得到的错误是:Cannot call method 'login' of undefined

authClient 似乎总是为空?我做错了什么?

【问题讨论】:

  • [Firebase 工程师] @Kato 是正确的,这是因为您获得的第一个回调(对于注销状态)正在同步调用。我将更改此行为,以便异步调用它,这应该可以解决您遇到的问题,尽管此处建议的所有其他解决方案也是正确的。

标签: authentication firebase


【解决方案1】:

这里 authClient 看起来不错。我认为 login() 函数的范围有问题。试试这个

    var myRootRef = new Firebase('https://url.firebaseIO.com/');
    var authClient = new FirebaseAuthClient(myRootRef, function(error, user) {
        if (error) {
            // an error occurred while attempting login
            console.log(error);
        } else if (user) {
            // user authenticated with Firebase
            console.log('User ID: ' + user.id + ', Provider: ' + user.provider);
        } else {
            // user is logged out

            console.log('logged out!');

        var email = "something@gmail.com";
        var password = "123";

        this.login('password', {
            email: email,
            password: password,
            rememberMe: true
        });
        }
    });

【讨论】:

  • 为什么我需要这样定义它?我在这里看到了一些其他的身份验证答案,它们不是那样的范围吗?他们调用了一个访问 auth 客户端并调用 login 函数的函数?
  • 像这个例子一样,它显示了范围界定,比如我是如何做到的,但它似乎对其他人有用? stackoverflow.com/questions/15167981/…
  • @TriFu 以我在下面的答案为基础,您在此处列出的示例有效的原因是,在单击按钮之前不会调用 authClient.login,从而为分配留出时间。
【解决方案2】:

当您最初调用new FirebaseAuthClient 时,它将使用当前登录状态调用回调(例如,当调用此状态时,用户可能已经登录)。这个回调发生在new FirebaseAuthClient返回之前,意味着authClient还没有被赋值。

您不需要在回调中移动您的authClient.login,尽管这样可以正常工作。您只需要注意这样一个事实,即第一次发出此回调可能是在分配之前。

例如,您可以在调用周围使用 setTimeout 以确保首先设置变量:

var authClient = new FirebaseAuthClient(myRootRef, function(error, user) {
    if (error) {
        // an error occurred while attempting login
        console.log(error);
    } else if (user) {
        // user authenticated with Firebase
        console.log('User ID: ' + user.id + ', Provider: ' + user.provider);
    } else {
        // user is logged out
        console.log('not logged in yet or logged out again!');
        setTimeout(login, 1);
    }
});

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 2014-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2021-04-05
    相关资源
    最近更新 更多