skip to Main Content

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?

3

Answers


  1. Chosen as BEST ANSWER

    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" />
    

  2. 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

    Login or Signup to reply.
  3. Try below code:

    import { Location } from '@angular/common';
    this.location.replaceState(this.location.path().replace('#!/', '');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search