重定向到Angularjs中的错误页面

zil*_*anu 12 angularjs angularjs-routing

我是AngularJs的新手.我有一个单页应用程序,其路由配置有控制器和视图.视图将加载<ng-view></ng-view>index.html页面元素中.在控制器内部,我正在http调用以获取数据并将数据绑定到$scope.对于成功方案,这可以正常工作但如果有错误,我如何插入另一个视图而不是在角度路径内配置的默认视图.请告诉我.

Yur*_*kiy 32

要实现处理ajax错误的常见方案,您可以根据错误状态实现自定义请求拦截器并将用户重定向到错误页面(或登录页面):

myApp.factory('httpErrorResponseInterceptor', ['$q', '$location',
  function($q, $location) {
    return {
      response: function(responseData) {
        return responseData;
      },
      responseError: function error(response) {
        switch (response.status) {
          case 401:
            $location.path('/login');
            break;
          case 404:
            $location.path('/404');
            break;
          default:
            $location.path('/error');
        }

        return $q.reject(response);
      }
    };
  }
]);

//Http Intercpetor to check auth failures for xhr requests
myApp.config(['$httpProvider',
  function($httpProvider) {
    $httpProvider.interceptors.push('httpErrorResponseInterceptor');
  }
]);
Run Code Online (Sandbox Code Playgroud)

这里的人物

  • 同意.这是在Angular应用程序中实现错误处理的更好,更通用的方法. (2认同)

Rag*_*dra 18

用于$location.url()在发生错误时重定向到404.html

$http.get(url,[params])
    .success(function(data, status, headers, config){
        // bind your data to scope
    })
    .error(function(data, status, headers, config) {
        $location.url('/404');
    });
Run Code Online (Sandbox Code Playgroud)

然后配置你的 $routeProvider

$routeProvider
    .when('/404', {
        templateUrl: '404.html',
        controller: 'Four04Controller'
    })
Run Code Online (Sandbox Code Playgroud)