AngularJS:首次加载页面时对给定的URL使用路由
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/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进入应用程序的每个用户。所以根本不需要上面的解决方案。
相关文章:
- 使用ui路由器实现动态URL路由的最佳方式是什么
- Ui路由器未按url路由
- 使用ui路由器在URL路由中创建一个必需的参数
- Javascript 无法解析正确的图像路径,当使用 URL 路由在 ASP.Net 中请求页面时
- AngularJS ui-router 中的 URL 路由参数
- 有没有一种方法可以在express.js中的url路由中执行动态键/值参数
- 使用正则表达式的Url路由子字符串
- Javascript(Jquery)调用MVC3 Controller/Action/ID的URL路由问题,返回404,
- Backbone.js:url路由末尾的尾部斜杠
- 在本地基于文件的应用程序中(使用file://),是否可以使用AngularJS进行HTML5模式URL路由
- Angular的url路由不能直接访问
- AngularJS为同一个URL路由多个ui-view
- 从Express服务的客户端React应用上的一致url路由
- 创建一个模板url路由脚本
- Url路由不工作在我的PHP代码
- Javascript MVC Url路由组件,路由在两边
- URL路由到子视图
- react-router-component将所有url路由到同一个组件
- Javascript将/url路由到函数
- AngularJS相对url路由问题