AngularJS:第一次加载页面时使用给定URL的路由

时间:2015-01-26 11:27:42

标签: javascript angularjs url-routing single-page-application

我使用AngularJS开发SPA。我的配置如下所示:

app.config(["$routeProvider",
    function($routeProvider) {
        return $routeProvider
            .when("/", {
                redirectTo: "/clients"
            }).when("/clients", {
                templateUrl: "app/views/crm/clients/list.html"
            }).when("/client/:id?", {
                templateUrl: "app/views/crm/clients/edit.html"
            }).when("/404", {
                templateUrl: "app/views/pages/404.html"
            }).otherwise({
                redirectTo: "/404"
            });
    }
]);

我想让我的用户共享客户端的网址:http://myapp.com/#/client/1http://myapp.com/#/client/2等。我们的想法是用户将URL写入位置栏并转到特定客户端的客户端页面。

当我尝试收听$routeChangeStart事件时,我发现第一次加载页面时事件回调中的current参数为空,而next.$$route.originalPath始终为/

$rootScope.$on('$routeChangeStart', function(event, next, current) {
      console.log(current);                   // undefined
      console.log(next.$$route.originalPath); // /
      console.log(next.$$route.redirectTo);   // /clients
});

那么如何才能将原始URL发送到服务器以使用请求的路由?

更新

事实证明,问题出在我自己的重定向中,这是在提取cookie的用户会话令牌时触发的。它会重定向到/每个使用会话cookie输入应用程序的用户。

2 个答案:

答案 0 :(得分:1)

您可以使用

document.URL  

$window.location

即:

 $rootScope.$on('$routeChangeStart', function(event, next, current) {
     console.log(document.URL);   
     console.log($window.location)       

});

请在此处查看演示 http://plnkr.co/edit/oaW40vWewxdZYxRkCW8c?p=preview

答案 1 :(得分:0)

最后,我想出了一个看似脏黑客的解决方案。

var app = angular.module('app', [ ... ]);

app.run(function (...) {

    ...

    var firstTimeLocationChanged = true;
    $rootScope.$on('$locationChangeStart', function(event, next, current) {
        var savedPath = current.split('#').slice(-1);
        if (firstTimeLocationChanged && ['/', '/login'].indexOf(savedPath) < 0) {
            firstTimeLocationChanged = false;
            setTimeout(function() {
                console.log('redirect to: ' + savedPath);
                $location.path(savedPath);
            }, 3000);
        }
    });

    ...

});

<强>更新

事实证明,问题出在我自己的重定向中,这是在提取cookie的用户会话令牌时触发的。它会重定向到/每个使用会话cookie输入应用程序的用户。所以根本不需要上面的解决方案。

相关问题