doubts with if Else in java script

Asked

Viewed 117 times

1

I’m using Angularjs and I have this method

$scope.login = function (email, usuario, senha) {
    $http.post("/Login/login", { email: email, usuario: usuario, senha: senha })
    .success(function (data) {
        debugger;

        if (data == "Empresa nao encontrada.") {
            UIkit.modal.alert(data, { labels: { 'Ok': 'OK' } });
            return;
        }
        else if (data == "Usuário ou Senha inválidos.") {
            UIkit.modal.alert(data, { labels: { 'Ok': 'OK' } });
            return;
        }
        else {
            window.sessionStorage.setItem('acessos', JSON.stringify(data));//coloca os acessos em uma sessão.storage
            window.location.href = '#/';
        }
    })
    .error(function (error) {
        alert("Erro");
    });
};

The Backend is returning "Company not found." this can be seen in the following image

inserir a descrição da imagem aqui

But the code of if (data == "Empresa nao encontrada.") {...} is not executed, only the code of the else, because?

  • I don’t know very well , I’m a beginner , but I believe it’s because the data that’s you’re picking up on .success(function (data) , is equal to the object you are passing on $http.post , then it can’t be that string "Empresa nao encontrada"

1 answer

2

The code

.success(function (data) {
    //...
}

Returns the following object:

date - {string|Object} - The Response body Transformed with the Transform functions.

status - {number} - HTTP status code of the Response.

headers - {Function([headerName])} - Header getter Function. config - {Object} - The Configuration Object that was used to generate the request.

statusText - {string} - HTTP status text of the Response.

Source


Therefore, for your code to work, you should refer to data which is where the answer itself is, thus:

if (data.data == "Empresa nao encontrada.") {
    UIkit.modal.alert(data, { labels: { 'Ok': 'OK' } });
    return;
} else if (data.data == "Usuário ou Senha inválidos.") {
    UIkit.modal.alert(data, { labels: { 'Ok': 'OK' } });
    return;
}
  • data.data did not work, date.date of Undefined error. To solve, I changed my return back, now returns 0 or 1, it worked, but the string comparison did not work, strange...

Browser other questions tagged

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