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

AngularJS: Use route for given URL when loading page first time

本文关键字:URL 路由 加载 AngularJS      更新时间:2023-09-26

我使用 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"
            });
    }
]);

我想让我的用户共享客户端的 URL: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进入应用程序的每个用户。

您可以使用

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

最后,

我想出了看起来像肮脏黑客但有效的解决方案。

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进入应用程序的每个用户。所以根本不需要上面的解决方案。