【问题标题】:Get route params from url从 url 获取路由参数
【发布时间】:2015-11-03 19:41:10
【问题描述】:

我正在尝试从重置密码电子邮件中的链接中检索重置密码令牌。该链接使用我试图获取的令牌将用户发送回我的节点/角度应用程序。

Laravel API:电子邮件模板

            <td class="content">
               <a href="http://localhost:3000/reset-password?token={{$token}}">Reset Your Password</a>
            </td>

Node/Angular 应用程序: ResetPassword.ejs 模板:我正在使用角度控制器:

<div ng-controller="resetPasswordCtrl">
    ...stuff
</div>

重置密码控制器:

'use strict';

angular
    .module('myApp')
    .controller('resetPasswordCtrl', ['$scope', '$routeParams', '$location', function($scope, $routeParams, $location) {

        console.log('ROUTE PARAMS', $routeParams); //object with a bunch of getters/setters
        console.log('ROUTE PARAMS', $routeParams.token); //undefined
        console.log('Location', $location.search('token'));  //LocationHashbangUrl
        console.log('Location', $location.search().token);  //true
        console.log('Location', $location.search()['token']); //true
        console.log('Route current params', $route); //empty route object 

    }]);

对于 LocationHashbangUrl ($location.search('token')),我知道我使用令牌获得了正确的 url,因为 $$absUrl 显示了它。

为什么我无法使用控制器中显示的方法之一检索 token 参数?

【问题讨论】:

  • 只有console.log($routeParams)你得到了什么?
  • @Erazihel 请看上面的编辑
  • 你能把你的路由器的代码贴出来吗?尝试使用$route 而不是$routeParams 像这样console.log($route.current.params);
  • @Erazihel 请参见上文

标签: javascript php angularjs node.js


【解决方案1】:

原来没有使用 html5/angular 路由,典型的方法

$location.search()
$routeParams

不会工作。

由于我正在传递参数并从外部访问我的节点应用程序(从 laravel 分发的电子邮件链接),我需要使用 javascript 解析 URI。

我找到了this resource,这很容易。因此,以下工作:

'use strict';

angular
    .module('myApp')
    .controller('resetPasswordCtrl', ['$scope', '$window', function($scope, $route, $window) {

        var getURIParams = function(variable) {
            var query = $window.location.search.substring(1);
            var vars = query.split('&');
            for (var i = 0; i < vars.length; i++) {
                var pair = vars[i].split('=');
                if (decodeURIComponent(pair[0]) == variable) {
                    return decodeURIComponent(pair[1]);
                }
            }
            console.log('Query variable %s not found', variable);
        };
        console.log('VAR', getURIParams('token')); //my token param
    }]);

【讨论】:

    【解决方案2】:

    你能发布你的 $routeProvider 吗?你可以在那里添加令牌作为参数,然后 $routeParams.token 会做你想做的事。像这样的:

    $routeProvider.when('/reset-password/:token')
    

    这意味着您的重置密码网址将如下所示:

    http://localhost:3000/reset-password/{{$token}}
    

    【讨论】:

    • Kip,我没有为我的应用程序使用 Angular 路由。我正在使用节点。令牌通过链接从我的 Laravel API 返回。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-03
    • 2011-11-10
    • 2019-08-11
    • 1970-01-01
    • 1970-01-01
    • 2016-12-28
    相关资源
    最近更新 更多