繁体   English   中英

如何使用UI-Router定义可选参数而不使用尾部斜杠?

[英]How to define optional parameter using UI-Router without trailing slash as well?

我正在努力将我的Angularjs代码从ng-router迁移到UI-Router。 在我的ng-router中我有可选参数但是我意识到在ui-router中不支持同样简单的方法来支持可选参数。 以下是我现有的ng-router模块的路由。

//Define routes for view  using ng-router
$routeProvider.
        when('/my-app/home/:userid?', {
            templateUrl: '/templates/partials/home/HomeView.html',
            controller: 'HomeViewController'
        })                   
        .when('/my-app/:productKey/:userid?', {
            templateUrl: '/templates/partials/productpage/ProductPageView.html',
            controller: 'ProductViewController'
        })
        .otherwise({redirectTo: '/my-app/home'});

注意:如果您看到“:userid”参数在这里非常顺利地实现为可选。

我尝试在ui-router中跟随但是同样不起作用。 我经历了很多帖子,建议复制路线。 我真的不想复制,因为它会使代码变脏。

//Set the default route

$urlRouterProvider.otherwise('/my-app/home');
//Define routes for view   (Please make sure the most matched pattern is define at top)
$stateProvider
        .state('viewallcards', {
            url: '/my-app/home/:userid',
            templateUrl: '/templates/partials/home/HomeView.html',
            controller: 'HomeViewController'
        })
        .state('productpage', {
            url: '/my-app/:productKey/:userid',
            templateUrl: '/templates/partials/productpage/ProductPageView.html',
            controller: 'ProductViewController'
        });

这里/ my-app / home /但是/ my-app / home不起作用。 怎么做也没有尾随斜线?

在同一个问题上关注帖子也让我感到惊讶,知道ui-router不支持这个。 它仍然有效吗? 请帮忙。

一个工作的例子

我们可以使用params : {} object来完全按照我们的需要定义userid (即准备省略)

在这里查看有关params更多详情:

Angular ui路由器在没有URL的状态之间传递数据

  $stateProvider
    .state('viewallcards', {
      url: '/my-app/home/:userid',
      params: { 
        userid: {squash: true, value: null }, // this will make both links below working:
        //         #/my-app/home
        //         #/my-app/home/
      },
      ...
    })
    .state('productpage', {
      url: '/my-app/:productKey/:userid',
      ...
    })

在这里检查它

默认情况下,UI路由器处于“严格模式” - 它区分具有尾部斜杠的路径和不具有斜杠的路径。 您可以通过禁用此模式关闭此功能:

当网址包含尾部斜杠时,如何激活我的路由?

在配置块中将strictMode设置为false:

$urlMatcherFactoryProvider.strictMode(false)

对于旧版本的ui-router,请将此代码段添加到模块的配置功能中。 它在$ urlRouterProvider上创建一个规则,该规则将所有缺少尾部斜杠的URL映射到同一个URL,但附加了斜杠。

使用此选项,最好将可选参数定义为home?userid=foo样式的URL参数home?userid=foo ,并设置您希望在URL中看到的内容。

来自UI-Router的Wiki

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM