简体   繁体   中英

Angular.js app: eliminate #! from the URLs of my single posts while keeping the slug

I am working on a small AngularJS blogging app (the framework version I use is 1.7.8).

I have managed to pull and display posts from an API I made myself.

I got stuck trying to eliminate #! from the URLs of my single posts while keeping the slug .

Example:

I have http://examplesite.eu/#!/europes-most-beautiful-castles and I tried to get http://examplesite.eu/europes-most-beautiful-castles .

This solution from the AngularJS docs does not work, as it completely eliminates the slug, and I want to keep it, for SEO purposes:

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

My app.js file:

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: '/'
    });
}]);

What's an alternative that would keep the slug in the post URL?

You need to use $locationProvider.html5mode to switch over to the history api so that angular can manipulate the URL more directly rather than using hashes.

You can read more about it in the documentation Hashbang and HTML5 Modes

Try below code:

import { Location } from '@angular/common';
this.location.replaceState(this.location.path().replace('#!/', '');

I have managed clean-up the URLs by using the $locationProvider service:

My app.js file:

angular.module('app', [
    'ngRoute',
    'app.controllers',
    'ngSanitize'
]).config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider){
    $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: '/'
    })

  $locationProvider.html5Mode({
    enabled: true,
    requireBase: true
  });
}]);

In index.html I added <base href="/"> :

<title>{{siteTitle}} | {{tagline}}</title>
<base href="/"> 
<meta charset="utf-8" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM