angularjs中的500 http状态路由

时间:2016-05-02 14:44:00

标签: angularjs

我有一个angularjs应用程序,我正在使用ui-router进行路由。

我的状态如下:

.state('core.page500', {
        url: '/page500',
        templateUrl: 'views/tmpl/pages/page500.html'
      })

我希望每当某个api调用在我的应用程序中返回500作为HTTP状态以将我路由到此状态时。

这在AngularJS中是否可行?

3 个答案:

答案 0 :(得分:1)

是的,有可能。 你需要做的是 创建一个自定义拦截器工厂,它检查response.status并运行重新路由代码,如果状态=== 500,并将其附加到angularJS http拦截器。

文档:https://docs.angularjs.org/api/ng/service/ $ http

尝试使用google搜索angularJS自定义http拦截器进行详细实施。

答案 1 :(得分:1)

你可以使用Http拦截器。我还没有测试过这个,所以请告诉我它是否有用,但这非常接近你所需要的:

angular.module('YourModule').factory('errorHttpInterceptor', ['$injector', '$q', '$state', errorHttpInterceptor]);

    function errorHttpInterceptor($injector, $q, $state) {
        return {
            responseError: function (error) {
                if (error.status === 500) {
                   $state.go('core.page500');
                }
                return $q.reject(error);
            }
        };
    }

然后将其添加到http管道中:

angular.module('YourModule').config(['$httpProvider', config]);

function config($httpProvider) {
   $httpProvider.interceptors.push('errorHttpInterceptor');
}

这将捕获所有500个错误并将用户发送到您的错误页面。

答案 2 :(得分:1)

查看名为Interceptors的概念。

您基本上创建的服务会在每次$ http调用时触发。它看起来如下:

 angular
  .module( 'interceptors', [])
  .factory('HttpInterceptors', HttpInterceptors);

HttpInterceptors.$inject = ['$q', '$injector'];

function HttpInterceptors($q, $injector) {
  return {
    // On request success
    request: function (config) {
      // console.log(config); // Contains the data about the request before it is sent.

      // Return the config or wrap it in a promise if blank.
      return config || $q.when(config);
    },

    // On request failure
    requestError: function (rejection) {
      //console.log('rejection', rejection); // Contains the data about the error on the request.

      // Return the promise rejection.
      return $q.reject(rejection);
    },

    // On response success
    response: function (response) {
      // console.log(response); // Contains the data from the response.

      // Return the response or promise.
      return response || $q.when(response);
    },

    // On response failture
    responseError: function (rejection) {
      if(rejection.status === 500) {
        var state = $injector.get('$state');
        state.go('core.page500');
      }

      // Return the promise rejection.
      return $q.reject(rejection);
    }
  };
}

然后,将其推送到应用的.config部分的$routeProvider内:

$httpProvider.interceptors.push('HttpInterceptors');