如何使用 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 中进行跟踪,但同样不起作用。我经历了很多post,有人建议复制路线。我真的不想复制,因为它会使代码变脏。

//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 无效。如何使它也没有尾部斜杠?

在同一问题上关注 post 令我惊讶的是 ui-router 不支持此功能。它还有效吗? 请帮忙。

a working example

我们可以使用params : {}对象来定义我们所需要的userid(即准备省略).

在此处查看有关 params 的更多详细信息:

  $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',
      ...
    })

检查一下in action here

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

How can I have my routes be activated when the url contains either a trailing slash or not?

Set strictMode to false in your config block:

$urlMatcherFactoryProvider.strictMode(false)

For older version of ui-router, add this snippet to your module's config function. It creates a rule on $urlRouterProvider that maps all urls that are missing a trailing slash to the same url but with the trailing slash appended.

使用这个,最好将你的可选参数定义为 home?userid=foo 风格的 URL 参数,并设置你总是希望在 URL 中看到的东西。

来自UI-路由器的Wiki