Skip to content Skip to sidebar Skip to footer

How To Handle Resource Not Found With Angularjs Routing

In a traditional data driven web application we often attempt to load a resource based on an ID passed in the URL. If the resource does not exist we return a 404 page. How should w

Solution 1:

I usually use ngRoute and provide resources through resovle:

angular.module('myApp').config(['$routeProvider', function($routeProvider) {
    $routeProvider.when('/phone/:phoneId', {
         templateUrl: 'views/phone.html',
         controller: 'PhoneDetailCtrl',
         resolve: {
             phone: ['$route', 'Phone', function($route, Phone) {
                 return Phone.get({ phoneId: $route.current.params.phoneId }).$promise
             }]
         }
    });
}]);

Now phone declared as dependency of this route and route won't be changed when response return an error. Then if you want to show error page you need listen to $routeChangeError event

angular.module('myApp').run(['$rootScope', '$location', function($rootScope, $location) {
   $rootScope.$on('$routeChangeError', function(event, current, previous, error) {
       if(error.status === 404) {
          $location.path('/404');
       }
   });
}]);

If you have multiple resources this approach allow you keep error handling code in one place and clear controllers from this logic that is very convenient

Solution 2:

Internally ngResource uses $http so to handle this kind of situations you could use http interceptors

Post a Comment for "How To Handle Resource Not Found With Angularjs Routing"