从URL中获取路由参数

4
我正在尝试从重置密码邮件中的链接中检索重置密码令牌。该链接将用户带回我的node/angular应用程序,并带有我正在尝试获取的令牌。 Laravel API: 邮件模板
            <td class="content">
               <a href="http://localhost:3000/reset-password?token={{$token}}">Reset Your Password</a>
            </td>

Node/Angular应用:ResetPassword.ejs模板:我正在使用一个Angular控制器:
<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显示了它。

enter image description here

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

当你只使用 console.log($routeParams) 时,你得到了什么? - Erazihel
@Erazihel 请查看上面的编辑。 - user3871
你能发布你的路由器代码吗?试着使用 $route 替代 $routeParams,像这样 console.log($route.current.params); - Erazihel
@Erazihel 请看上面。 - user3871
2个回答

0
你能发布你的$routeProvider吗?你可以在那里添加token作为参数,然后$routeParams.token就可以实现你想要的功能。像这样:
$routeProvider.when('/reset-password/:token')

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

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

Kip,我的应用程序没有使用Angular路由,而是使用Node。令牌通过链接从我的Laravel API返回。 - user3871

0
原来在不使用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
    }]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接