Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle angular-ui-router and template loading errors?

Using angular-ui-router, I have something like:

.state('page', {
    url: '/page',
    templateUrl: '/page.html'
})

This template URL may return a "401 Unauthorized". Is it possible to handle the http response when the router tries to load the url and handle it, so I can show some message or redirect the user?

like image 981
Natan Avatar asked Jun 30 '26 00:06

Natan


1 Answers

You can register an interceptor for your application. The implementation of this interceptor

    $httpProvider.responseInterceptors.push([
      '$q',
      '$location',
      '$rootScope',
     (function($q, $location, $rootScope) {
  return {
    responseError: function(response) {
      if (response.status === 401) {
          console.log(response.status + ' intercepted');
          $location.path('/unauthorized/');
          $q.reject(response);
      }
      return response;
    }
  };
});
]

After this you need to register /unauthorized in your states with a custom page template.

like image 175
asaad Avatar answered Jul 05 '26 06:07

asaad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!