Verifying route preconditions prior to loading controller

前端 未结 4 700
广开言路
广开言路 2021-02-15 17:27

I\'m writing a single page application in Angular, specifically angular.dart, but I\'m assuming this question still applies to AngularJS.

Take for example the followin

4条回答
  •  青春惊慌失措
    2021-02-15 18:24

    I know that following solution is not applicable to Angular.Dart, but still is worth to mention solution for ui-router:

    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(user) {
        // ...
      }
    });
    });
    app.run(function($rootScope, $state, $currentUser) {
    $rootScope.$on('$stateChangeStart', function(e, to) {
    if (!angular.isFunction(to.data.rule)) return;
    var result = to.data.rule($currentUser);
    
    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});
    }
    });
    });
    

提交回复
热议问题