我在有角度的应用程序中使用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;

最佳答案

谢谢大家得到了解决方案。我正在广播$stateChangeError本身的AuthorizationError。这只是一个变通办法,如果有其他方法可以实现此目的,我将发布答案(除了拒绝deferredresolve中的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)
        })
      }
    }

09-20 12:53