在Angular JS中保护路线

时间:2016-10-30 19:05:40

标签: javascript angularjs

我正在开发一个Angular应用程序,该应用程序调用外部API进行登录验证。

我要成功调用用于登录和注销的API,我将其用于将布尔值放入本地存储(因此它会在刷新时保留)。

我觉得这可能是实现这一目标的一种非常糟糕的方式。 Angular有更好的方法吗?

我的实施:

app.js

var module = angular
  .module('myApp', [
    'ngRoute',
    'ngTouch',
    'LocalStorageModule'
  ])
  .config(function ($routeProvider, $locationProvider, localStorageServiceProvider) {
 $routeProvider
 ...
 .when('/protectedroute, {
  ...
 resolve: {
  'auth': function(Auth) {
     return Auth.authorized(); 
  }

 }
})

}

验证服务:

angular.module('myApp')
  .service('Auth', function ($http, $q, $window, $location, localStorageService) {

    var isLogged = localStorageService.get('isLogged');
    console.log(isLogged);
    return {
      authorized: function() {
        if (!localStorageService.get('isLogged')) {
          console.log('DENY');
          $location.path('/');
        } else {
          console.log('ALLOW');
        }
      }
    }
  });

登录服务:

angular.module('myApp')
  .service('Login', function ($http, $q, $window, $location, localStorageService) {
    return {
      login: function (username, password) {
        var reqLogin = {
          method: 'POST',
          url: 'url_api',
          data: $.param({
            'user[email]': username,
            'user[password]': password
          }),
          headers: {
            ...
          }
        }

        $http(reqLogin).then(function successCallback(response) {
          console.log('success!');
          console.log(response);
          localStorageService.set('isLogged', true);
          localStorageService.set('user[email]', username);
          console.log(localStorageService.get('isLogged'), localStorageService.get('user[email]'));


          $location.path('/profile');

        }, function errorCallback(response) {
          console.log('failure');
          console.log(response);
        });
      },
      logout: function() {
        var reqLogout = {
          method: 'DELETE',
          url: 'url_api',
          headers: {
            ...
          }
        }

        $http(reqLogout).then(function successCallback(response) {
          console.log('success!');
          console.log(response);
          localStorageService.set('isLogged', false);
          console.log(localStorageService.get('isLogged'), localStorageService.get('user[email]'));

          $location.path('/');

        }, function errorCallback(response) {
          console.log('failure');
          console.log(response);
        });
      }
    };

  });

0 个答案:

没有答案