如果特定 stateParam 为空,如何重定向到 state

2024-06-20

我不确定我这样做的方式是否正确,任何建议将不胜感激。

我有一个餐厅选择器,用户可以从中选择一家餐厅。然后所有其他子状态加载特定于所选餐厅的内容。但我需要默认选择一个子状态,包括一家餐厅,它将根据用户最近的位置或 cookie 数据(如果他们之前选择过)来选择。但是,我不确定如何在不知道餐厅 ID 的情况下默认重定向到子状态?

下面是我的代码的私生版本来说明。

app.config(function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/restaurant/[some id based on cookie info]/our-food"); // if no id is set, then I want to get it from a cookie, but then how do i do the redirect?

$stateProvider
    .state('restaurant', {
        url: '/restaurant/:restaurantId',
        template: "<ui-view/>",
        controller: function($state, $stateParams, Data, RestaurantService, $cookieStore) {
            if(typeof $stateParams.restaurantId !== 'undefined') {
                                  // get the restaurantID from the cookie
                            }
        }
    })
    .state('restaurant.our-food', {
        url: '/our-food',
        templateUrl: function($stateParams) {
        return 'templates/food-food.html?restaurantId=' + $stateParams.restaurantId;
        },
    controller: 'SubNavCtrl'
    })
    .state('restaurant.glutenfree-vegetarian', {
        url: '/glutenfree-vegetarian',
        templateUrl: function($stateParams) {
    return 'templates/food-vegetarian.html?restaurantId=' + $stateParams.restaurantId;
        },
    controller: 'SubNavCtrl'
    })

下面的图片说明了前端发生的情况: www.merrywidowswine.com/ss.jpg


我会创建一个事件,每次打开该特定状态时都会触发该事件。

查看他们的文档:https://github.com/angular-ui/ui-router/wiki#onenter-and-onexit-callbacks https://github.com/angular-ui/ui-router/wiki#onenter-and-onexit-callbacks

所以我的猜测是这样的

1.onEnter回调到餐厅状态(推荐)

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

我自己从来没有使用过这样的事件,所以你可能需要下定决心做一些体操,但我相信这是最干净、最容易理解和最可维护的解决方案。

2 全局onStateChangeStart事件全局事件(尽管每次状态更改都会触发该事件)

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

3 在控制器中或者,如果您想像开始一样使用控制器。

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

就开发而言,这可能是最快的解决方案,但我相信使用事件更干净,并且可以使代码更易于理解。

Note:我实际上没有运行过任何代码,所以它可能不起作用,它只是伪代码,可以让您了解该去哪里。如果您遇到问题,请告诉我。

EDIT:实际上我不确定状态参数是否传递到控制器。您可能必须使用解析才能访问它们。

EDIT:要访问 onEnter 回调或控制器中的 stateParams,我相信您必须使用解析:

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

请参阅有关解决的 ui-router 文档以获取更多示例/更好的解释

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如果特定 stateParam 为空,如何重定向到 state 的相关文章

随机推荐