简体   繁体   English

.then未在devicesIsReady上定义

[英].then is not defined on devicesIsReady

I'm getting the following error: 我收到以下错误:

Uncaught TypeError: loginService.verificarSesion(...).then is not a function 未被捕获的TypeError:loginService.verificarSesion(...)。then不是一个函数

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. 我需要检查用户是否在我的apache-cordova应用程序的deviceIsReady上登录。 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. 在您的代码中很明显,函数verificarSesion可以返回一个空数组,当然,数组没有.then()方法。

According to the doc here , your call to localStorageService.get(usuario) return whatever value you stored in the localStorage . 根据此处的文档,您对localStorageService.get(usuario)调用将返回您存储在localStorage中的任何值。 Are you sure that you store a Promise with the key 'usuario' ? 您确定使用密钥'usuario'存储Promise吗?

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? 上面的代码还有很多问题,例如, usuariologueado用于什么? what is the token ? 什么是token why do you get the user session directly from localStorage with something seems to be the username ? 为什么为什么直接从localStorage获取用户会话,似乎是username etc 等等

If you want a user session, you can look at sessionStorage instead of localStorage . 如果要进行用户会话,可以查看sessionStorage而不是localStorage

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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