如何处理angular-ui-router和模板加载错误?

时间:2015-10-29 15:22:36

标签: angularjs angular-ui-router

使用angular-ui-router,我有类似的东西:

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

此模板网址可能会返回“401 Unauthorized”。当路由器尝试加载URL并处理它时,是否可以处理http响应,这样我可以显示一些消息或重定向用户?

1 个答案:

答案 0 :(得分:2)

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.