简体   繁体   中英

.then is not defined on devicesIsReady

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!

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM