toState.Url值不是嵌套状态的绝对哈希值

toState.url value is not an absolute hash for nested states

本文关键字:哈希值 状态 嵌套 Url toState      更新时间:2023-09-26

我试图在$stateChangeStart事件中获得toState对象的url状态basic.tasks:

  $rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
                ...
                   console.log(toState.name);  // > basic.tasks
                   console.log(toState.url);   // > /tasks
                ...
            }

状态配置:

 $stateProviderRef
 .state('basic',{
         url: '/b',
         template: require('source/basic/templates/basic.html'),
         controller: 'BasicController',
         abstract: true
         })
 .state('basic.tasks', {
         url: '/tasks',
         template: require('source/basic/templates/tasks/tasks.html'),
         controller: 'TasksController',
       })

toState的值。url是/tasks而不是/b/tasks。有没有办法得到完整的哈希包括父状态。

我尝试了$window.location.hash,但它只给出了fromState的完整哈希路径,因为它不会更新,直到状态改变完成。

没有简单的方法来做到这一点,除非你只是添加父状态到url,但如果你正在寻找一个更动态的方式,那么这可能是一个选择。我不确定你是否在你的url中有标签(通常它在那里,在这里我们使用它只是为了regexp删除标签-但它看起来像这样http://localhost:8100/#/app在localhost),但如果你这样做,你可以尝试这样的东西:

$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
  var href = $state.href(toState.name);
  var regexp = new RegExp('#','g');
  href = href.replace(regexp, '');
  console.log(href);
});

如果你的url中有一些状态的参数,你可以用toParams将它们添加到绝对url中,因为stateChangeStart上的这个函数不会将参数添加到url中。它将直接在stateChangeSuccess上工作。

编辑:

正如Ganesh Matkam在评论部分所说,实际上有一个简单的解决方案,可以将stateParams包含到url中。就像这样简单:

$rootScope.$on("$stateChangeStart", function (event, toState, toParams, fromState, fromParams) {
  var href = $state.href(toState.name, toParams);
  var regexp = new RegExp('#','g');
  href = href.replace(regexp, '');
  console.log(href);
});