首页 > 解决方案 > Angular.js 应用程序:消除 #! 来自我的单个帖子的 URL,同时保持 slug

问题描述

我正在开发一个小型 AngularJS 博客应用程序(我使用的框架版本是 1.7.8)。

我已经设法从我自己制作的 API 中提取和显示帖子。

在保留 slug 的同时#!试图从我的单个帖子的 URL 中删除。

例子:

我有http://examplesite.eu/#!/europes-most-beautiful-castles并且我试图得到http://examplesite.eu/europes-most-beautiful-castles.

AngularJS 文档中的这个解决方案不起作用,因为它完全消除了蛞蝓,我想保留它,用于 SEO 目的:

appModule.config(['$locationProvider', function($locationProvider) {
  $locationProvider.hashPrefix('');
}]);

我的 app.js 文件:

angular.module('app', [
    'ngRoute',
    'app.controllers',
    'ngSanitize'
]).config(['$routeProvider', function($routeProvider){
    $routeProvider.when('/', {
        templateUrl: 'templates/posts.html',
        controller: 'PostsController'
    }).when('/:slug', {
        templateUrl: 'templates/singlepost.html',
        controller: 'SinglePostController'
    }).when('/page/:id', {
        templateUrl: 'templates/page.html',
        controller: 'PageController'
    }).otherwise({
        redirectTo: '/'
    });
}]);

有什么替代方法可以将 slug 保留在帖子 URL 中?

标签: javascriptangularjsroutesngroute

解决方案


您需要使用$locationProvider.html5mode切换到历史 API,以便 Angular 可以更直接地操作 URL,而不是使用哈希。

您可以在文档Hashbang 和 HTML5 模式中了解更多信息


推荐阅读