抛出自定义错误时触发$ stateChangeError

时间:2017-06-21 11:47:35

标签: javascript angularjs angular-ui-router

我在角度应用程序中使用UI路由。 检查每个州的授权。在授权的情况下,抛出自定义错误。我希望$stateChangeError能够处理从$stateChangeStart抛出的任何自定义错误。

$stateChangeStart

 $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState) {
      $log.info("Route change start from", fromState.url, "to", toState.url);
       $rootScope.isAuthorized = authorize(toState);

          if ($rootScope.isAuthorized) {
            $log.info('is Authorized')
          } else {
            $log.info('not Authorized');
            throw new AuthorizationError()
          }
        });

    });

自定义错误

  function AuthorizationError(description) {
      this.message = "Forbidden";
      this.description = description || "User authentication required.";
    }
    AuthorizationError.prototype = Object.create(Error.prototype);
    AuthorizationError.prototype.constructor = AuthorizationError;

1 个答案:

答案 0 :(得分:1)

谢谢你们得到了解决方案。我是从$stateChangeError本身广播AuthorizationError的。这只是一个解决方法,如果有任何其他方法可以实现这一点,我会发布答案(除了拒绝deferred resolve中的state

function AuthorizationError(description, code) {
      this.message = "Forbidden";
      this.description = description || "User authentication required.";
      this.code = code || 'NOT_AUTHENTICATED';
      $rootScope.$broadcast('$stateChangeError', $rootScope.state.to, $rootScope.state.toParams, $rootScope.state.from, $rootScope.state.fromParams, this);
    }

<强> rootscope.state

var transitionTo = $state.transitionTo;
$state.transitionTo = function(to, toParams, options) {
      var from = $state.$current,
        fromParams = $state.params;

      to = to.name ? to : $state.get(to);

      $rootScope.state = {
          to: to.self,
          toParams: toParams,
          from: from.self,
          fromParams: fromParams,
          options: options
        }

           return transitionTo(to, toParams, options)
        })
      }
    }