[英]AngularJS: Use route for given URL when loading page first time
我使用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/1
: http://myapp.com/#/client/1
: http://myapp.com/#/client/2
等。这个想法是用户将URL写入位置栏并转到特定客户的客户页面。
当我尝试监听$routeChangeStart
事件时,我发现在第一次和next.$$route.originalPath
一次首次加载页面时,事件回调中的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以使用请求的路由?
UPDATE
事实证明,问题出在我自己的重定向中,该重定向是从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);
}
});
...
});
UPDATE
事实证明,问题出在我自己的重定向中,该重定向是从Cookie中提取用户会话令牌时触发的。 它重定向到/
谁进入与会话cookie应用程序的每个用户。 因此,根本不需要上述解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.