基于HTTP查询防止ui-router中的状态更改

时间:2016-03-24 19:51:33

标签: angularjs angular-ui-router

如何防止特定"到#34;的状态变化? ui-router中的状态(是否使用onEnter?)假设我有这条路径:

.state('auth.confirm', {
  url: '/confirm/:resetToken',
  template: '<confirm-page></confirm-page>',
  data: { pageTitle: 'Confirm Reset', specialClass: 'gray-bg' }
})

以及使用此基于承诺的函数的此服务:

validateResetToken: function(resetToken) {
  var self = this;
  var deferred = $q.defer();

  $http.post(AppConstants.hostRootUrl + '/auth/reset/validate', { resetToken: resetToken })
    .then(function(response) {
      if(response.data && response.data.success) {
        // if we got a 200 return and it indicates success in the response, resolve
        self.message = 'Success';
        deferred.resolve(self.message);
      }
      else if (response.data && !response.data.success && response.data.error) {
        // if we got a 200 return, but success is falsey and there's an error message, reject with that message
        self.message = response.data.error;
        deferred.reject(self.message);
      }
      else {
        // error with generic message
        self.message = 'Unknown response. Contact administrator.';
        deferred.reject(self.message);
      }
    }, function(errPost) {
      if (errPost.data && errPost.data.error) {
        self.message = errPost.data.error;
        deferred.reject(self.message);
      }
      else {
        self.message = 'Could not connect.';
        deferred.reject(self.message);
      }
    });

  return deferred.promise;
},

2 个答案:

答案 0 :(得分:3)

对于后人(和Google员工)来说,Alon Eitan让我再次看一下我的ContentPresenter方法,我意识到我添加resolve导致被拒绝的承诺不会渗透。最终的代码有效:

catch()

答案 1 :(得分:0)

您可以在https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#how-to-create-rules-to-prevent-access-to-a-state

中创建规则

调整他们的例子:

app.config(function($stateProvider) {
  $stateProvider.state('privatePage', {
    data: {
      rule: function(token) {
        return validateResetToken(token)
      }
  });
});
app.run(function($rootScope, $state, $stateParams) {
  $rootScope.$on('$stateChangeStart', function(e, to) {
    if (!angular.isFunction(to.data.rule)) return;
    var result = to.data.rule($stateParams.resetToken);

    if (result && result.to) {
      e.preventDefault();
      // Optionally set option.notify to false if you don't want 
      // to retrigger another $stateChangeStart event
      $state.go(result.to, result.params, {notify: false});
    }
  });
});