小编典典

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

angularjs

我给人的印象是Angular会重写出现在临时模板中定位标记的href属性中的URL,以便无论在html5模式还是hashbang模式下它们都可以工作。位置服务文档似乎说HTML链接重写可以解决哈希问题。因此,我希望当不在HTML5模式下时,将插入哈希,而在HTML5模式下,则不会。

但是,似乎没有进行任何重写。以下示例不允许我仅更改模式。应用程序中的所有链接都需要手工重写(或在运行时从变量派生。我是否需要根据模式手动重写所有URL?

我没有看到在Angular
1.0.6、1.1.4或1.1.3中进行任何客户端url重写。似乎所有的href值都必须在#/之前添加为hashbang模式,在//之前添加为html5模式。

是否需要一些配置才能引起重写?我在读文档吗?还在做傻事吗?

这是一个小例子:

<head>
    <script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.1.3/angular.js"></script>
</head>

<body>
    <div ng-view></div>
    <script>
        angular.module('sample', [])
            .config(
        ['$routeProvider', '$locationProvider',
            function ($routeProvider, $locationProvider) {

                //commenting out this line (switching to hashbang mode) breaks the app
                //-- unless # is added to the templates
                $locationProvider.html5Mode(true);

                $routeProvider.when('/', {
                    template: 'this is home. go to <a href="/about"/>about</a>'
                });
                $routeProvider.when('/about', {
                    template: 'this is about. go to <a href="/"/>home</a'
                });
            }
        ])
            .run();
    </script>
</body>

附录:在重读我的问题时,我发现我使用了“重写”一词,但对于谁和何时进行重写没有足够的明确性。问题在于如何使 Angular
在呈现路径时重写URL,以及如何使 Angular 在两种模式下统一解释JS代码中的路径。这 不是
关于如何使Web服务器做HTML5兼容的要求重写。


阅读 249

收藏
2020-07-04

共1个答案

小编典典

该文档对AngularJS路由不是很清楚。它讨论了Hashbang和HTML5模式。实际上,AngularJS路由以三种模式运行:

  • Hashbang模式
  • HTML5模式
  • HTML5模式下的Hashbang

对于每种模式,都有各自的LocationUrl类(LocationHashbangUrl,LocationUrl和LocationHashbangInHTML5Url)。

为了模拟URL重写,您实际上必须将html5mode设置为true并装饰$ sniffer类,如下所示:

$provide.decorator('$sniffer', function($delegate) {
  $delegate.history = false;
  return $delegate;
});

我现在将更详细地解释这一点:

Hashbang模式

组态:

$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
});
$locationProvider
  .html5Mode(false)
  .hashPrefix('!');

当您需要在HTML文件(例如,

<a href="index.html#!/path">link</a>

在浏览器中,您必须使用以下链接: http://www.example.com/base/index.html#!/base/path

如您所见,在纯Hashbang模式下,HTML文件中的所有链接都必须以诸如“ index.html#!”之类的开头。

HTML5模式

组态:

$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
  });
$locationProvider
  .html5Mode(true);

您应该在HTML文件中设置基础

<html>
  <head>
    <base href="/">
  </head>
</html>

在这种模式下,您可以使用HTML文件中不带#号的链接

<a href="/path">link</a>

浏览器中的链接:

http://www.example.com/base/path

HTML5模式下的Hashbang

当我们实际使用HTML5模式但在不兼容的浏览器中时,会激活此模式。通过装饰$
sniffer服务并将历史记录设置为false,我们可以在兼容的浏览器中模拟此模式。

组态:

$provide.decorator('$sniffer', function($delegate) {
  $delegate.history = false;
  return $delegate;
});
$routeProvider
  .when('/path', {
    templateUrl: 'path.html',
  });
$locationProvider
  .html5Mode(true)
  .hashPrefix('!');

在HTML文件中设置基础:

<html>
  <head>
    <base href="/">
  </head>
</html>

在这种情况下,也可以在HTML文件中不包含哈希的情况下编写链接

<a href="/path">link</a>

浏览器中的链接:

http://www.example.com/index.html#!/base/path
2020-07-04