我正在学习AngularJS,有一件事真的让我很恼火。

我使用$routeProvider为我的应用程序声明路由规则:

$routeProvider.when('/test', {
  controller: TestCtrl,
  templateUrl: 'views/test.html'
})
.otherwise({ redirectTo: '/test' });

但是当我在浏览器中导航到我的应用程序时,我看到app/#/test而不是app/test。

所以我的问题是为什么AngularJS把这个散列#添加到url ?有可能避免吗?


当前回答

**

建议使用HTML 5样式(PathLocationStrategy)作为 Angular中的位置策略

** 因为

它产生干净和SEO友好的url,更容易 便于用户理解和记忆。 您可以利用服务器端呈现,这将使 通过在服务器中呈现页面,我们的应用程序加载速度更快 首先,在将它交付给客户端之前。

只有在必须支持旧的策略时才使用hashlocationstrategy 浏览器。 点击这里了解更多

其他回答

try

$locationProvider.html5Mode(true)

更多资料请浏览 locationProvider美元 使用美元的位置

你也可以使用下面的代码重定向到主页(主页):

{ path: '', redirectTo: 'home', pathMatch: 'full'}

在如上所述指定重定向后,您可以重定向其他页面,例如:

{ path: 'add-new-registration', component: AddNewRegistrationComponent},
{ path: 'view-registration', component: ViewRegistrationComponent},
{ path: 'home', component: HomeComponent}

如果你像其他人说的那样启用了html5mode,并创建一个包含以下内容的.htaccess文件(根据你的需要进行调整):

RewriteEngine   On
RewriteBase     /
RewriteCond     %{REQUEST_URI} !^(/index\.php|/img|/js|/css|/robots\.txt|/favicon\.ico)
RewriteCond     %{REQUEST_FILENAME} !-f
RewriteCond     %{REQUEST_FILENAME} !-d
RewriteRule     ./index.html [L]

当用户进入正确的路线时,他们将被引导到你的应用程序,你的应用程序将读取路线,并将他们带到正确的“页面”。

编辑:只要确保没有任何文件或目录名称与您的路由冲突。

在Angular 6中,你可以使用路由器:

RouterModule.forRoot(routes, { useHash: false })

让我们写下看起来简单而简短的答案

在路由器中添加html5Mode(true);

app.config(function($routeProvider,$locationProvider) {

    $routeProvider.when('/home', {
        templateUrl:'/html/home.html'
    });

    $locationProvider.html5Mode(true);
})

在html头部添加基本标签

<html>
<head>
    <meta charset="utf-8">    
    <base href="/">
</head>

感谢@plus-详细介绍了上面的答案