【问题标题】:Angularjs: $routeChangeStart custom property coming as undefined on $location.pathAngularjs:$routeChangeStart 自定义属性在 $location.path 上未定义
【发布时间】:2015-06-26 07:06:31
【问题描述】:

我在 $routeProvider 中使用自定义属性来检查是否需要登录,并在 $routeChangeStart 事件中检查它。它在正常的 URL 更改上运行良好,但如果我使用 $location.path 更改 URL,则 custom property 将作为未定义的。任何人都知道如何使用 k$location.path 获取自定义属性

 $routeProvider.when('/result', {
                templateUrl: 'partials/result.html',
                controller: 'ResultCtrl',
                data: {
                    requireLogin: true
                }
            });
 $rootScope.$on('$routeChangeStart', function (event, next, current) {
        var requireLogin = false;
        if (next['data']) {
            requireLogin = next.data.requireLogin
        }

正常重定向(使用锚点 href)next.data.requireLogin 正在工作。但是,如果我用 $locaion.path 更改 URL,它会以未定义的形式出现。

谢谢, 乌德什

【问题讨论】:

  • 您必须使用路径或查询参数才能从 url 重定向中获取值。自定义参数仅通过使用 href 或 $state.go 的角度状态更改传递
  • 但是这个参数我不能作为查询参数传递...
  • 你在哪里需要 $location.path 以及为什么不使用 $state.go 之类的其他方法?
  • 尝试在控制器上使用 $state.current.data.requireLogin
  • 我设置了类似$location.path('/result') 的路径,将其更改为$location.path('result') 成功了....

标签: angularjs angularjs-routing


【解决方案1】:

您通过 $location.path 设置的 path 可能是错误的?如果 path 找到自定义 data 对象,我找不到任何问题。如果 path 与其中一条路线不匹配 - 那么我得到一个 undefined 异常。我也会为 next 添加一个空检查。

Plunker

if (next && next['data'])

【讨论】:

  • 太棒了!谢谢伙计...我正在设置路径,例如$location.path('/result') 将其更改为$location.path('result') 成功了....
【解决方案2】:

问题在于我设置 $location.path() 的方式。我正在设置路径,如

$location.path('/result')

改成

$location.path('result')

成功了……

仅在 '/' 中记录的所有地方...不确定哪个是正确的方法,但它解决了我的问题。谢谢:)

【讨论】:

    猜你喜欢
    • 2013-06-27
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    • 2011-03-27
    • 1970-01-01
    • 2014-09-16
    相关资源
    最近更新 更多