处理Angular UI路由器中的错误

时间:2014-11-14 11:44:56

标签: angularjs angular-ui-router

在服务器端,我有一个下一个方法,检查数据库中是否找到了令牌:

def method(token) 
   if (Database.find(token).length == 0)
     not_found()
   else
     success()
end

url为token/:token,例如token/123

我有一个州:

   $stateProvider.state('token', {
     url: '/token/:token',
     templateUrl: 'success'
   }).state('404', {
      url: '/404',
      templateUrl: 'notfound'
   });

但我不知道,如何在ui路由器检查令牌,我需要一些这样的

$http.post('/token', {token: $stateParams.token}).success(function(){  
     //ok continue and load `success` template
}).error(function(){
    $state.go('404'); //when error
});

是否可以使用ui路由器?

1 个答案:

答案 0 :(得分:1)

我也有同样的情况,这就是我做的事情

.when('/beacon/:beacon_id',{
        templateUrl : 'components/beacon/beacon.html',
        controller : 'beaconController',
        access : { requiredLogin: true },
        resolve : {
            Beacon : ['$route', 'BeaconService', function($route, BeaconService){
                var beacon = BeaconService.beacon();
                return beacon.get({'beacon_id':$route.current.params.beacon_id}, function(successResponse){
                    console.log(successResponse.result[0]);
                    return successResponse.result[0];
                }, function(errorResponse){
                    $location.path('blablabla'); // This will redirect me to 404. :P
                });
            }] 
        }
    })
.otherwise({templateUrl : '404.html'});

在控制器中

App.controller('beaconCtrl', ['Beacon', '$scope', function(Beacon, $scope){
    //Get Beacon into controller than get your promise.
    Beacon.$promise.then(function(data){
        $scope.beacon = data.result[0];
    });
}]);