AngularJS:如何使用深度链接启用$locationProvider.html5Mode



当通过$locationProvider.html5Mode(true)在AngularJS中启用html5Mode时,当您登录到网站更深的页面时,导航似乎会发生倾斜。

例如:

  • http://www.site.com
    当我导航到根目录时,我可以点击网站中的所有链接,Angular的$routeProvider将接管网站导航并加载正确的视图。

  • http://www.site.com/news/archive
    但是当我导航到这个url时(或者当我在上面的深度链接上时点击刷新…),这个导航并没有像我预期的那样工作。首先,正如$locationProvider.html5Mode的Documentation所指定的,我们捕获服务器上的所有URL,类似于angular中的otherwise路由,并返回与根域相同的html。但是,如果我从角度的run函数中检查$location对象,它会告诉我http://www.site.com是我的host/archive是我的path$routeProvider到达.otherwise()子句,因为我只有/news/archive作为有效路由。这个应用程序会做一些奇怪的事情。

也许服务器上的重写需要以不同的方式进行,或者我需要指定angular中的内容,但目前我不知道为什么angular是不包括/news段的路径。

示例main.js:

// Create an application module
var App = angular.module('App', []);
App.config(['$routeProvider', '$locationProvider', function AppConfig($routeProvider, $locationProvider) {
    $routeProvider
        .when(
        '/', {
            redirectTo: '/home'
        })
        .when('/home', {
            templateUrl: 'templates/home.html'
        })
        .when('/login', {
            templateUrl: 'templates/login.html'
        })
        .when('/news', {
            templateUrl: 'templates/news.html'
        })
        .when('/news/archive', {
            templateUrl: 'templates/newsarchive.html'
        })
        // removed other routes ... *snip
        .otherwise({
            redirectTo: '/home'
        }
    );
    // enable html5Mode for pushstate ('#'-less URLs)
    $locationProvider.html5Mode(true);
    $locationProvider.hashPrefix('!');
}]);
// Initialize the application
App.run(['$location', function AppRun($location) {
    debugger; // -->> here i debug the $location object to see what angular see's as URL
}]);

编辑根据请求,服务器端的更多详细信息:服务器端由zend框架的路由组织,它处理自己的路由(用于在特定的/apiurl上向前端提供数据,最后,如果没有绑定特定的其他路由,则有一个catch-all路由,它提供与根路由相同的html。所以它基本上是为深度链接路由上的主页html服务的。

更新2在研究了这个问题后,我们注意到这种路由在Angular 1.0.7稳定版上运行良好,但在Angular 1.1.5不稳定版中显示了上述行为。

我已经检查了更改日志,但到目前为止还没有发现任何有用的东西,我想我们可以将其作为bug提交,或者将其作为与他们所做的某个更改相关的不必要行为提交,或者只是等待,看看它是否在稍后发布的稳定版本中得到修复。

发现那里没有错误。只需添加:

<base href="/" />

到您的<head />

这是我花了很多时间才找到的最好的解决方案。基本上,将target="_self"添加到每个需要确保页面重新加载的链接中。

http://blog.panjiesw.com/posts/2013/09/angularjs-normal-links-with-html5mode/

这个问题是由于使用了AngularJS 1.1.5(它不稳定,显然有一些错误或与1.0.7中不同的路由实现)

将其恢复到1.0.7立即解决了问题。

我尝试过1.2.0rc1版本,但还没有完成测试,因为我不得不重写一些路由器功能,因为他们把它从核心中删除了。

无论如何,在使用AngularJS版本1.0.7时,这个问题已经得到了修复。

  1. 配置AngularJS

$location/在html5和hashbang模式之间切换/链接重写

  1. 配置服务器:

https://github.com/angular-ui/ui-router/wiki/Frequently-Asked-Questions#wiki-如何配置您的服务器使用html 5模式进行工作

我的问题用这些解决了:

1-把这个添加到你的脑海中:

<base href="/" />

2-在app.config 中使用

$locationProvider.html5Mode(true);

最新更新