【问题标题】:angular.js url routing and html5Mode(true)angular.js url 路由和 html5Mode(true)
【发布时间】:2016-03-09 07:45:36
【问题描述】:

我想设置由 angular.js 路由的可访问和可收藏的 URL。

该应用程序只是整个网站的一部分,可通过http://example.com/application/访问

/application/ 之后的都是路由参数。

现在我想要一个可以通过以下方式访问的 URL

http://example.com/application/#/filter1/filter2/filter3/
                               ^ hashbang here

http://example.com/application/filter1/filter2/filter3/
                              ^ no hashbang here

我希望 angular.js 将我的路由参数传递给我的应用程序,但我却通过 .otherwise 路由。

基本路线设置

$locationProvider.html5Mode(true); // this requires base-tag to be set in dom, 
                                   // but doesnt work for me

$routeProvider
    .when('/application/:filter1/:filter2/:filter3', {
        action: 'filter',
        reloadOnSearch: false
    })
    .otherwise({
        redirectTo: '/application/' + filter1 + '/' + filter2 + '/' + filter3
    });

在该应用程序的 HTML 中,我输入了 <base href="/application/" />,这似乎可以正常工作,但是在通过 .otherwise-route 后重新加载页面或重新访问它不起作用并且服务器说“找不到页面”。

当我禁用 HTML5 模式并删除 base-tag 时,它也不起作用,我会通过 .otherwise 路由

【问题讨论】:

  • 您的服务器有责任在 /application/ 和 /application/filter1/filter2/filter3/ 请求上响应同一页面,而您没有在服务器端提供任何详细信息。
  • 好的,但是用 hashbang 路由怎么样?也不起作用-而是采用 .otherwise-route

标签: javascript angularjs url angular-routing hashbang


【解决方案1】:

发生这种情况是因为您的服务器知道application/(并且可能返回application.html)但不知道application/filter1/filter2/filter3/(因为filter3.html 不存在)。

你可以:

  • 决定只使用哈希语法(服务器读取# 之前的所有内容,并让浏览器(在您的情况下为 Angular)来管理之后的所有内容。
  • 设置您的服务器,使以application/* 开头的每个路径都返回到浏览器application.html

此外,我认为您需要从路由提供者中删除基础:

$routeProvider
.when('/:filter1/:filter2/:filter3', {
    action: 'filter',
    reloadOnSearch: false
})
.otherwise({
    redirectTo: '/' + filter1 + '/' + filter2 + '/' + filter3
});

【讨论】:

  • 谢谢。我不想碰服务器设置。相反,angular 应该在 # 之后获取所有内容并将其用作参数,但事实并非如此,而是我得到 charAt(d) 未定义。当我调试一点时,我得到 $$.parse withoutbaseUrl 左右,这似乎关心 hashbang 并且在我的情况下失败
  • 感谢 squaleLis,我已经为哈希设置了 URL 重写,现在它工作得很好!
猜你喜欢
  • 2014-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-22
相关资源
最近更新 更多