lito
lito

Reputation: 989

Handle errors in Angular UI Router

On server side i have a next method, which check if token found in database:

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

url as token/:token, for example token/123

I have a state for it:

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

But i do not know, how to in ui router check token, i need some like this

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

Is it possible with ui router?

Upvotes: 0

Views: 426

Answers (1)

CrazyGeek
CrazyGeek

Reputation: 3437

I also had the same situation, This is what I did

.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'});

In controller

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];
    });
}]);

Upvotes: 1

Related Questions