Navigation errors in AngularJS can occur due to:
- Unauthorized access
- Invalid routes
- API failures while resolving data
- Server issues
To handle these, we use $routeChangeError
, fallback routes, and $location.path()
for redirection.
1️⃣ Defining a Fallback Route (otherwise()
)
A fallback route ensures users are redirected to a default page if they enter an unknown URL.
app.config(function($routeProvider) {
$routeProvider
.when('/home', {
templateUrl: 'home.html',
controller: 'HomeCtrl'
})
.when('/dashboard', {
templateUrl: 'dashboard.html',
controller: 'DashboardCtrl'
})
.otherwise({
redirectTo: '/home' // Redirects to home if the route is not found
});
});
Explanation:
- If a user navigates to a non-existent route, they are redirected to
/home
. - This prevents users from seeing a blank or error page.
2️⃣ Handling Errors with $routeChangeError
When a route fails to load (e.g., API failure in resolve
), $routeChangeError
helps handle errors gracefully.
Example: Handling API Failures in Resolved Data
app.config(function($routeProvider) {
$routeProvider
.when('/profile', {
templateUrl: 'profile.html',
controller: 'ProfileCtrl',
resolve: {
userData: function(UserService, $q) {
return UserService.getUserData().catch(function(error) {
return $q.reject('Data Load Failed'); // Trigger $routeChangeError
});
}
}
});
});
🔹 If UserService.getUserData()
fails, the route won’t load and triggers $routeChangeError
.
Catching Errors with $routeChangeError
app.run(function($rootScope, $location) {
$rootScope.$on('$routeChangeError', function(event, current, previous, rejection) {
console.error('Route Error:', rejection);
$location.path('/error'); // Redirect to a custom error page
});
});
If data fails to load, users are redirected to /error
.
3️⃣ Redirecting Unauthorized Users ($routeChangeStart
)
Unauthorized users should be redirected before the route changes.
Example: Redirecting Users Without Permission
app.run(function($rootScope, $location, AuthService) {
$rootScope.$on('$routeChangeStart', function(event, next) {
if (next.requiresAuth && !AuthService.isAuthenticated()) {
event.preventDefault(); // Stop navigation
$location.path('/login'); // Redirect to login
}
});
});
🔹 Prevents unauthorized users from accessing restricted routes.
4️⃣ Handling Broken Links with a Custom 404 Page
Instead of redirecting to home, show a 404 error page.
Example: Custom 404 Route
app.config(function($routeProvider) {
$routeProvider
.when('/404', {
templateUrl: '404.html'
})
.otherwise({
redirectTo: '/404'
});
});
Users see a 404 error page instead of being redirected to home.
Summary
- Use
otherwise()
to redirect users from invalid routes. - Handle errors with
$routeChangeError
and redirect users to an error page. - Use
$routeChangeStart
to stop unauthorized users from accessing routes. - Create a custom 404 error page for broken links.