理解AngularJS promise API的问题 - AuthenticationService

时间:2016-06-07 22:00:34

标签: javascript angularjs cordova ionic-framework angular-promise

大家晚上好。我首先使用AngularJS,Ionic& amp;创建一个移动应用程序。几周前科尔多瓦。我尝试使用给定的API为此应用程序创建AuthenticationService。 我检查了一些教程并创建了它,它似乎除了承诺处理之外还有效。我那里有赤字。 也许有人帮助我:)。

我在这里处理对某些页面/状态的访问。

$rootScope.$on('$stateChangeStart', function (event, next, nextParams, fromState) {

    if ('data' in next && 'authorizedRoles' in next.data) {
        var authorizedRoles = next.data.authorizedRoles;
        if (!AuthService.isAuthorized(authorizedRoles)) {
            event.preventDefault();
            $state.go($state.current, {}, {
                reload: true
            });
            $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
        }
    }
    if (next.name == 'app.admin' || next.name == 'app.bonus') {

        AuthService.isAuthenticated().then(function (response) {


        }, function (response) {
            var alertPopup = $ionicPopup.alert({
                title: 'Error1!',
                template: 'Sorry, You have to login again.'
            });
            event.preventDefault();
            $state.go('app.login');

            $log.log(response + '1er');
        });

    }

});

我执行用户登录

.controller('LoginCtrl', function ($scope, $ionicPopup, AuthService, $state, $log, $q) {
$scope.data = {};


$scope.login = function (data) {

    $q.all([
    AuthService.login(data.username, data.password),
    AuthService.isAuthenticated()
]).then(function (data) {
        console.log(data[0]); 
        console.log(data[1]); 

        if (data[0] == false) {
            var alertPopup = $ionicPopup.alert({
                title: 'Error!',
                template: 'Sorry, You have to login again.'
            });
        }

        if (data[1] == true) {
            $state.go('app.bonus', {}, {
                reload: true
            });
        } else {
            var alertPopup = $ionicPopup.alert({
                title: 'Error!',
                template: 'Sorry, You have to login again.'
            });
        }

    });


};

})

在这里,我创建了处理用户角色,验证和服务的服务。创建cookie - 每个API调用都需要一个也创建的随机数

.service('AuthService', function ($q, $http, USER_ROLES, $log) {
var link = 'http://example/api/';
var username = '';
var isAuthenticated = false;
var role = '';
var mycookie = '';
var mynonce = '';

function checkCookie() {


    mycookie = window.localStorage.getItem('LOCAL_COOKIE');
    $log.info(mycookie);
    if (mycookie) {

        $http.get(link + 'get_nonce/?controller=user&method=generate_auth_cookie&insecure=cool').then(
            function (result) {
                if (result.data.status == "ok") {
                    mynonce = result.data.nonce;
                    $log.info(mynonce);
                } else {
                    return false;
                }
            },
            function (err) {
                return false;
            });

        $http.get(link + 'user/validate_auth_cookie/?cookie=' + mycookie + '&nonce=' + mynonce + '&insecure=cool').then(
            function (result) {
                if (result.data.status == "ok") {
                    return true;
                } else {
                    window.localStorage.removeItem('LOCAL_COOKIE');
                    return false;
                }
            },
            function (err) {
                return false;
            });

    } else {
        return false;
    }
}


function doLogin(name, pw) {

    var loginAttempt = false;

    $http.get(link + 'get_nonce/?controller=user&method=generate_auth_cookie&insecure=cool').then(
        function (result) {
            if (result.data.status == "ok") {
                mynonce = result.data.nonce;
                $log.info(mynonce);
            } else {
                loginAttempt = false;
            }
        },
        function (err) {
            loginAttempt = false;
            $log.info(err);
        });


    mycookie = $http.get(link + 'user/generate_auth_cookie/?username=' + encodeURIComponent(name) + '&password=' + encodeURIComponent(pw) + '&nonce=' + mynonce + '&insecure=cool').then(
        function (result) {
            if (result.data.status == "ok") {
                mycookie = result.data.cookie;
                loginAttempt = true;
                username = name;
                if (username == 'MarkusK') {
                    role = USER_ROLES.admin
                } else {
                    role = USER_ROLES.public
                }
                window.localStorage.setItem('LOCAL_COOKIE', mycookie);
                $log.info(mycookie);
            } else {
                loginAttempt = false;
            }
        },
        function (err) {
            loginAttempt = false;
            $log.info(err);
        });

    $log.info('test1' + loginAttempt);

    return loginAttempt;

};

var login = function (name, pw) {
    return $q(function (resolve, reject) {
        if (doLogin(name, pw)) {
            resolve('Login success.');
        } else {
            reject('Login Failed.');
        }
    });
};

var validCookie = function () {
    return $q(function (resolve, reject) {
        if (checkCookie()) {
            resolve('Cookie success.');
        } else {
            reject('Cookie Failed.');
        }
    });
};


var logout = function () {
    mycookie = undefined;
    username = '';
    isAuthenticated = false;
    window.localStorage.removeItem('LOCAL_COOKIE');
};

var isAuthorized = function (authorizedRoles) {
    if (!angular.isArray(authorizedRoles)) {
        authorizedRoles = [authorizedRoles];
    }
    return (checkCookie() && authorizedRoles.indexOf(role) !== -1);
};



return {
    login: login,
    logout: logout,
    isAuthorized: isAuthorized,
    isAuthenticated: validCookie,
    username: function () {
        return username;
    },
    role: function () {
        return role;
    }
};

})

也许有人有时间帮助我,我终于理解了promise API。 谢谢。

1 个答案:

答案 0 :(得分:0)

这里有一个很好的插图定义:

http://andyshora.com/promises-angularjs-explained-as-cartoon.html

让我们说我们有以下代码(并不意味着它只是解释诺言概念):

var a = 1; 
a = foo();
a = a + 2;

因为JavaScript是异步的,所以第二条指令(对 foo()的调用)不会阻塞该线程。

如果 foo() 等待其他资源(来自服务器的值),它将不会等待并进入第三条指令(a = 2)

这个承诺用于告诉JavaScript线程:“当我准备就绪时你不会忘记复出,你答应我:)”。