Check Angularjs Login and Password

Asked

Viewed 395 times

1

I have the following login function:

function login(username, password, callback) {
        var myResponse;
        var systemUser;

        Users.getByLogin(username)
        .then(function (response) {
            systemUser = response.data;
        });

        // Linha testada
        console.log("Senha: " + systemUser.password);
        console.log("Senha informada: " + password);

        if (typeof systemUser == "undefined") {
            myResponse = { success: false, message: "Usuário inexistente!" };
        } else if (password == systemUser.password) {
            myResponse = { success: true, user: systemUser };
        } else {
            myResponse = { success: false, message: "Usuário ou senha incorretos!" };
        }

        callback(myResponse);
    }

Usually the error occurs TypeError: Cannot read property 'password' of undefined.

If I declare the variable systemUser out of function , noting the line of the comment Linha testada, the value gives Undefined the first time I call the method, but the second time passes.

1 answer

1


This happens because the method Users.getByLogin() is asynchronous.

Your error occurs because at the time the line console.log("Senha: " + systemUser.password); the return of getByLogin has not occurred yet; systemUser is still a null variable.

Once the result is returned, the function specified in .then() will be executed. Modify your code as suggested below:

function login(username, password, callback) {
    var myResponse;
    var systemUser;

    Users.getByLogin(username)
    .then(function (response) {
        systemUser = response.data;

        // Linha testada
        console.log("Senha: " + systemUser.password);
        console.log("Senha informada: " + password);

        if (typeof systemUser == "undefined") {
            myResponse = { success: false, message: "Usuário inexistente!" };
        } else if (password == systemUser.password) {
            myResponse = { success: true, user: systemUser };
        } else {
            myResponse = { success: false, message: "Usuário ou senha incorretos!" };
        }

        callback(myResponse);
    });
}
  • I forgot even this synchronization issue, really AJAX queries are asynchronous! Thank you!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.