0

I'm getting the following error:

Uncaught TypeError: loginService.verificarSesion(...).then is not a function

I think I don't understand perfectly promise

I need to check if the user is logged in on deviceIsReady on my apache-cordova app. This is the part of the function:

.run(function($ionicPlatform, $http, $state, loginService) {
    $ionicPlatform.ready(function() {

        loginService.verificarSesion()
            .then(function(usuario) {
                if(usuario == 1){
                    //es complejo
                    $state.go('app.home');
                }
                else if(usuario == 2){
                    //es usuario comun
                    $state.go('app.home-usuario');
                }
                else{
                    //no se renococió ningún usuario válido
                    $state.go('app.login');
                }
            })
            .catch(function(e){
               console.log('error trying to find the user');
            });
    });
})
.config(function($urlRouterProvider) {
    // if none of the above states are matched, use this as the fallback
    $urlRouterProvider.otherwise('/app/login');
});

Service:

(function() {
    'use strict';

    angular
        .module('example.login')
        .factory('loginService', loginService);

    loginService.$inject = ['$http','remoteDataService', '$q','_','localStorageService'];

    /* @ngInject */
    function loginService($http, remoteDataService, $q,_, localStorageService){ 
        var token = 'token';
        var usuario = 'usuario';

        var service = {
            verificarSesion: verificarSesion
        };
        return service;

        //funcion para saber si hay una sesión activa
        function verificarSesion() {
            var usuariologueado = localStorageService.get(token) || [];
            if (usuariologueado == []){
                return [];
            }
            return localStorageService.get(usuario);
        }

        //generar error si hubo un problema
        function generarError(e){
            if (e.message) {
                return $q.reject(e.message);
            }
            return $q.reject('Hubo un problema al conectarse al servidor. Intente nuevamente.');
        }

    }
})();

If the user is logged in I have to sen the user to another view.

What I'm doing wrong? Thanks!

Faustino Gagneten
  • 2,564
  • 2
  • 28
  • 54
  • The indentation here is inconsistent and it's making your code hard to follow. Why are you indenting the closing brackets on `if`? This is an extremely unruly style. The reason I'm complaining is because callback and promise-driven code needs to be very carefully nested or it won't work out like you expect. – tadman Jan 16 '17 at 23:33
  • I copied the code to sublime tex and it change the identation @tadman – Faustino Gagneten Jan 16 '17 at 23:41
  • I'm assuming your `localStorageService.get()` method does not return a promise, just a value immediately? – GregL Jan 16 '17 at 23:43
  • @GregL Well... is a component, I used it like the tutorial said. I think may be not return a promise. I think this is the component: https://github.com/grevory/angular-local-storage – Faustino Gagneten Jan 16 '17 at 23:46
  • 1
    from the documentation - **get** `Directly get a value from local storage` ... wrap `localStorageService.get(usuario);` in a `Promise.resolve()` – Jaromanda X Jan 16 '17 at 23:48

1 Answers1

0

It's pretty clear in your code that the function verificarSesion can return an empty Array, of course an Array doesn't have .then() method.

According to the doc here, your call to localStorageService.get(usuario) return whatever value you stored in the localStorage. Are you sure that you store a Promise with the key 'usuario'?

I suppose you would need something like this:

    function verificarSesion() {
        var usuariologueado = localStorageService.get(token) || [];

        if (usuariologueado == []){
            return new Promise(function (res, rej) {
                $http
                    // change this if you need to post application/x-www-form-urlencoded
                    .post('login_url', {username: usuario, password: 'abc'})
                    .then(
                        function (resp) {
                            // initiate the session in the localStorage
                            localStorageService.set(usuario, resp.data);
                            res(localStorageService.get(usuario));
                        },
                        function(err) {
                            // error occured, notify user
                            rej(err);
                        }
                    );
            });
        }
        return new Promise(function (res, rej) {
            // resolve immediately
            res(localStorageService.get(usuario));
        });
    }

There are still many issues with the code above, for instance, what is usuariologueado used for? what is the token? why do you get the user session directly from localStorage with something seems to be the username? etc

If you want a user session, you can look at sessionStorage instead of localStorage.

Mr. Duc Nguyen
  • 1,049
  • 7
  • 16