angularjs小试

//测试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();
});

你可能感兴趣的:(angularjs小试)