Login with SQLite and $http.get()


#1

I’m beginning with Ionic and AngularJS.
I have a problem to create my login controller, that will do a search in SQLite to locate users. If don’t locate the users, i will execute a request in my API that return a JSON data.

Probably, my difficulty is with promises and resolves. The sequence of my commands are not performed as they should.

I need that function “efetuarLogin()” follow this steps, all inside a loading indicator:

  1. Search the users in local database;
  2. Search the users in API (if necessary) and insert result into local database;
  3. Validate the user;

With my code, the API request is executed only after validate user!

Sorry my poor english…

Services (DB):

.factory('Repositorio', function ($cordovaSQLite, $q, $ionicPlatform) {
var self = this;

self.query = function (query, parameters) {
    parameters = parameters || [];
    var q = $q.defer();

    $ionicPlatform.ready(function () {
        $cordovaSQLite.execute(db, query, parameters)
          .then(function (result) {
              q.resolve(result);
          }, function (error) {                
              q.reject(error);
          });
    });
    return q.promise;
}

self.obterTodos = function (result) {
    var retorno = [];

    for (var i = 0; i < result.rows.length; i++) {
        retorno.push(result.rows.item(i));
    }
    return retorno;
}

return self;
})

.factory('RepositorioSupervisores', function ($cordovaSQLite, Repositorio) {
var self = this;

self.obterTodos = function () {
    return Repositorio.query("SELECT id, nome, login, senha FROM supervisores")
        .then(function (resultado) {
            return Repositorio.obterTodos(resultado)
        });
}

self.adicionar = function (supervisor) {
    var campos = [supervisor.id, supervisor.nome, supervisor.login, supervisor.senha];
    return Repositorio.query("INSERT INTO supervisores (id, nome, login, senha) VALUES (?,?,?,?)", campos);
}

self.removerTodos = function () {        
    return Repositorio.query("DELETE FROM supervisores");
}

return self;
});

Service (API):

.factory('ServicoSupervisores', function ($http, $q) {

const url = 'http://myAPIurl';
var self = this;
var retorno = [];

self.obterSupervisores = function () {
    return $http.get(url).then(function (response) {
        return response.data;
    });
}    

return self;
})

Controller:

.controller('LoginCtrl', function ($scope, $state, ServicoSupervisores, RepositorioSupervisores, $ionicLoading, ionicMaterialInk, $http, $cordovaSQLite) {
$scope.supervisores = [];

$scope.login = {
    usuario: '',
    senha: ''
};

$scope.efetuarLogin = function () {

    $ionicLoading.show({
        content: 'Atualizando lista de usuários',
        animation: 'fade-in',
        showBackdrop: true,
        maxWidth: 200,
        showDelay: 0
    });

    //load the users in DB
    $scope.carregarSupervisores();

    //if don't have users, start API request
    if ($scope.supervisores.length == 0) {

        ServicoSupervisores.obterSupervisores().then(function (response) {
            $scope.supervisores = response;
        }, function (e) {
            console.log(e);
        });            
        
        //add the result in local database
        for (var i = 0; i < $scope.supervisores.length; i++) {
            RepositorioSupervisores.adicionar($scope.supervisores[i]);
        }            
    };

    //function to validate the user;

    $ionicLoading.hide();        
}
})

#2

I was wrong to use in my controller other functions after the function that resolved the request.

Now, it’s ok.