Angular登录验证使用Web worker怎么样?

时间:2016-08-28 09:12:16

标签: angularjs angularjs-authentication

您如何看待这种方法

使用web worker进行角度登录/身份验证

它看起来很擅长我,这样你就可以摆脱

$ rootScope事件:)

这只是一个更生产方式的例子 你应该像https://stackoverflow.com/a/16730809

一样使用

Html& JS

<html ng-app="app">
    <head>
        <meta charset="utf-8">
        <title>Form</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    </head>
    <body ng-controller="LoginController as vm">
      <p ng-if="vm.isLogged">Logged as {{vm.username}}</p>
      <a href ng-click="vm.doFakeLogin()">Login</a>

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0-rc.2/angular.min.js">
    </script>
    <script>

    function LoginController($scope){
        var vm = this;
        vm.isLogged = false;
        var workerCheckLogin = new Worker('worker-check-login.js');
        var workerDoLogin = new Worker('worker-do-login.js');
        var jwt = 'auth-token';
        workerCheckLogin.postMessage(jwt); 
        workerCheckLogin.addEventListener('message', function(e) {
            if(e.data > 0){
                $scope.$evalAsync(function() {
                    vm.isLogged = true; 
                    vm.username = 'Whisher';
                });
            }
        }, false);
        vm.doFakeLogin = function doFakeLogin(){
            workerDoLogin.postMessage({username:'whisher','password':'12345'});
        }
        workerDoLogin.addEventListener('message', function(e) {
            if(e.data > 0){
                $scope.$evalAsync(function() {
                    vm.isLogged = true; 
                    vm.username = 'Whisher';
                });
            }
        }, false);
    }
    angular
    .module('app', [])
    .controller('LoginController',LoginController);
    </script>   
    </body>
</html>

工人检查-login.js

self.addEventListener('message', function(e) {
  console.log('Worker check login said: ', e.data);
  /*
   do xhr to the server
   e.data = jwt 
   return 
   1 succees
   0 fail 
  */
  self.postMessage(0); // 
}, false);

工人-DO-login.js

self.addEventListener('message', function(e) {
  console.log('Worker do login said: ', e.data);
  /*
   do xhr to the server
   e.data = credentials
   return 
   1 succees
   0 fail 
  */
  self.postMessage(1); // 
}, false);

0 个答案:

没有答案