2

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

我快到了,但它不是很有效。我遇到的问题如下:如果用户去#/articles/my-articles/,他们会被转发到#/login/?next=%2Farticles%2F:module%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);
        }
    });
}]);

我可以使用 hacky 方式获得原始路径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'
    });
}]);

我该如何解决这个问题?

4

2 回答 2

1
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 视图,您可能必须提供otherwise路线:(
取决于您的 $locationProvider 配置)

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

...

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

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

于 2013-11-27T12:55:27.130 回答
0

我的解决方案适用于 Angular 1.2.13:preventDefault 停止角度路由,并且 $window.location 将我发送到登录页面。这适用于 ASP.NET MVC + Angular 应用程序。

$rootScope.$on("$locationChangeStart", function (event, next, current) {
                    event.preventDefault();
                    $window.location = '/Login';
            }        
    });
于 2014-04-04T20:21:36.863 回答