How to redirect to state if specific stateParam is empty

前端 未结 2 1121
悲哀的现实
悲哀的现实 2021-02-01 03:48

I\'m not sure if the way I am doing it is correct, any advice would be appreciated.

I have a Restaurant Selector, which the user can select a restaurant from. Then all o

2条回答
  •  你的背包
    2021-02-01 04:31

    I would create an event that is fired every time you open that specific state.

    Check out their doc: https://github.com/angular-ui/ui-router/wiki#onenter-and-onexit-callbacks

    So my guess is either something like this

    1. onEnter callback to restaurant state (recommended)

    $stateProvider.state("contacts", {
      template: '',
      resolve: ...,
      controller: function($scope, title){
      },
      onEnter: function(){
        if(paramNotSet){ $state.go(...)}
      }
    });
    

    I've never used an event as such myself so you might have to do some gymnastics with resolve, but I believe this is the cleanest, easiest to understand and most maintainable solution.

    2 Global onStateChangeStart event A global event (although this would get fired for every state change)

    $rootScope.$on('$stateChangeStart', 
    function(event, toState, toParams, fromState, fromParams){ ... //check cookie, change state etc ...})
    

    3 In the controller Alternatively If you want to use the controller like you started doing.

    controller: ['$state', '$stateParams', 'Data', 'RestaurantService', '$cookieStore', 
    function($state, $stateParams, Data, RestaurantService, $cookieStore) {
        if(typeof $stateParams.restaurantId !== 'undefined') {
            sate.go('restaurant', $cookieStore['restaurant'])
        }
    }]
    

    This is probably the fastest solution in terms of development but I believe using events is cleaner and makes for more understandable code.

    Note: I haven't actually run any of this code so it might not work, it's just pseudo-code to give you an idea of where to go. Let me know if you run into issues.

    EDIT: Acutally I'm not sure if stateParams are passed on to the controller. You might have to use resolve to access them.

    EDIT: to access stateParams in onEnter callback or the controller, I believe you have to use resolve as such:

        resolve: {
             checkParam: ['$state','$stateParams', '$cookieStore', function($state, $stateParams, $cookieStore) {
    //logic in here, what it returns can be accessed in callback or controller.
             }]
    

    see the ui-router doc on resolve for more examples/better explanation

提交回复
热议问题