How to decorate current state resolve function in UI-Router? Current function isn't invoked

后端 未结 2 1561
借酒劲吻你
借酒劲吻你 2020-12-10 08:32

I\'m trying to DRY in $stateProvider and prevent adding the same auth function in each resolve. I\'ve created decorator that in each state change w

2条回答
  •  星月不相逢
    2020-12-10 09:29

    I realized that $delegate.current object contains only raw stateProvider config data. To wrap resolve function I add my function to $delegate.$current on each state change.

    $provide.decorator('$state', function($delegate, $rootScope) {
      $rootScope.$on('$stateChangeStart', function(event, state, params) {
        if ($delegate.current === "err404" || $delegate.current === "login" || $delegate.current === "register") {
          return;
        }
        console.log("decorator", $delegate);
        $delegate.$current.resolve["auth"] = ['AuthService', '$stateParams', function(AuthService, $stateParams) {
          if (AuthService.isAuthenticated()) {
            console.log('AuthService.me()');
            return AuthService.me();
          } else {
            return false;
          }
        }]
      });
      return $delegate;
    });
    

    Update

    I found related discussion on github, you can add universal resolve function into toState param:

    app.run(['$rootScope', '$state',
      function($rootScope, $state) {
    
        $rootScope.$on('$stateChangeStart', function(event, toState) {
    
          if (toState.name === "login" || toState.name === "register") {
            return;
          }
    
          toState["resolve"]["auth"] = ['AuthService', '$stateParams', function(AuthService, $stateParams) {
            if (AuthService.isAuthenticated()) {
              return AuthService.me();
            } else {
              return false;
            }
          }];
        });
      }
    ]);
    

提交回复
热议问题