Angularjs小試験

2829 ワード

// token
var app = angular.module('myApp', ['ngRoute']);
// , token  3
app.config(function($httpProvider){
  // 
  var intercepter=function($q,$rootScope,Auth){
    return{
      'response':function(resp){
        if(resp.config.url=='/login'){
          // API 
          Auth.setToken(resp.data.token);
        }
        return resp;
      },
      'responseError':function(rejection){
        // 
        switch(rejection.status){
          case 401:
            if(rejection.config.url!=='api/login')
            // 
              $rootScope.$broadcast('auth:loginRequired'); break;
          case 403:
            $rootScope.$broadcast('auth:forbidden'); break;
          case 404:
            $rootScope.$broadcast('page:notFound'); break;
          case 500:
            $rootScope.$broadcast('server:error'); break;
        }
      }
    }//return
  };//intercepter
  $httpProvider.interceptors.push(intercepter);
});
app.config(function($routeProvider,ACCESS_LEVELS){
  $routeProvider.when('/', {templateUrl: 'HTTPBasic.html', reloadOnSearch: false});
  $routeProvider.when('/count', {templateUrl: 'count.html', reloadOnSearch: false});
  $routeProvider.otherwise({ redirectTo:'/'});
});
// 1
app.constant('ACCESS_LEVELS',{
  pub:1,
  user:2
});

// 2
app.factory('Auth',function($cookieStore,ACCESS_LEVELS){
    var _user=$cookieStore.get('user');
    var setUser=function(user){
      if(!user.role||user.role<0){
        user.role=ACCESS_LEVELS.pub;
      }
      _user=user;
      $cookieStore.put('user',_user);
    }
    return {
      isAuthorized:function(lvl){ // 
        return _user.role>=lvl;
      },
      setUser: setUser,
      isLoggedIn: function(){
        return _user?true: false;
      },
      getUser: function(){
        return _user;
      },
      getId: function(){
        return _user? _user._id:null;
      },
      getToken: function(){
        return _user? _user.token:'';
      },
      setToken: function(token){ // 
        _user._token=token;
      },
      logout:function(){
        $cookieStore.remove('user');
        _user=null;
      }
    };
});

// 
app.service('Backend',function($http,$q,$rootScope,Auth){
  this.getDashboardData=function(){
    $http({
      method:'GET',
      url:'http://localhost:8080/bbwbg/userController/list',
      params:{ taken:Auth.getToken(),name:'fd'}
    }).success(function(data){
      return data.data;
    }).catch(function(reason){
      $q.reject(reason);
    });
  };
});
app.controller('MainController',function($scope,Backend){
  $scope.name="heha";
  Backend.getDashboardData();
});