gpt4 book ai didi

javascript - AngularJS:转发到登录页面进行身份验证,保留路由作为 GET 参数?

转载 作者:行者123 更新时间:2023-11-30 05:42:06 25 4
gpt4 key购买 nike

我是一个 Angular 新手。我正在尝试编写一个 Angular 服务,它可以在任何页面上检查用户是否已登录,如果没有,则将他们转发到登录页面,将他们的当前路径作为 GET 参数传递

我快到了,但还不太行得通。我遇到的问题如下:如果用户转到 #/articles/my-articles/,他们将被转发到 #/login/?next=%2Farticles%2F:模块 %2F

换句话说,看起来 Angular 正在传递路由模式,而不是实际的 URL。

这是我的验证码:

auth.run(['$rootScope', '$location', '$user', 'TOKEN_AUTH', 'PROJECT_SETTINGS', function ($rootScope, $location, $user, TOKEN_AUTH, PROJECT_SETTINGS) {
var MODULE_SETTINGS = angular.extend({}, TOKEN_AUTH, PROJECT_SETTINGS.TOKEN_AUTH);
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if (next.$$route && !next.$$route.anonymous && !$user.authenticated) {
var nextParam = next.$$route.originalPath;
$location.url(MODULE_SETTINGS.LOGIN + '?next=' + nextParam);
}
});
}]);

我可以使用 current.params.module 以一种奇怪的方式获得原始路径 - 但这对我没有帮助,因为 routeChangeStart 似乎被触发了几次次并且 current 对象在除最后一次火灾之外的所有情况下都是未定义的。

这是我的路线文件:

articles.config(['$routeProvider', function ($routeProvider) {
$routeProvider
.when('/articles/:module/', {
templateUrl: 'views/articles/article_list.html',
controller: 'ArticlesListCtrl'
})
.when('/articles/:module/:id/', {
templateUrl: 'views/articles/article_detail.html',
controller: 'ArticlesDetailCtrl'
});
}]);

我该如何解决这个问题?

最佳答案

auth.run(['$rootScope', '$location', '$user', 'TOKEN_AUTH', 'PROJECT_SETTINGS', function ($rootScope, $location, $user, TOKEN_AUTH, PROJECT_SETTINGS) {
var MODULE_SETTINGS = angular.extend({}, TOKEN_AUTH, PROJECT_SETTINGS.TOKEN_AUTH);
$rootScope.$on('$routeChangeStart', function (e, next, current) {
if (!$user.authenticated) {
$location.url(MODULE_SETTINGS.LOGIN + '?next=' + $location.path());
$location.replace();
}
});
}]);

如果登录不是 AngularJS View ,您可能必须提供一个otherwise 路由:
(取决于您的 $locationProvider 配置)

$routeProvider.otherwise({
template: 'Redirecting…',
controller : 'Redirect'
});

...

articles.controller('Redirect', ['$location', function($location) {
if (someConditionThatChecksIfUrlIsPartOfApp) {
location.href = $location.path();
return;
} else {
// Show 404
}
}]);

旁注:您不应该阅读以 $$ 为前缀的属性,它们是私有(private)的 AngularJS 变量。
另请注意:不要在您自己的代码中使用 $ 前缀 ($user),这些是公共(public)属性,为 AngularJS 保留。

关于javascript - AngularJS:转发到登录页面进行身份验证,保留路由作为 GET 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20242182/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com