Adam Young
Adam Young

Reputation: 1331

Remove trailing slashes in Angularjs

I found this snippet in one of the other stack overflow questions.

$urlRouterProvider.rule(function($injector, $location){
  let path = $location.path();
  let hasTrailingSlash = path[path.length-1] === '/';
  if(hasTrailingSlash) {
    console.log('coming in the has trailing slash rule function');
    let normalizedPath = path.substr(0, path.length - 1);
    $location.replace().path(normalizedPath);
  }
});

I have some urls in the following forms /school/:id, /school, /:id, /class/:id

The above function works perfectly fine if I enter a url in the form /class/121/ and it redirects to /class/121, similarly /about-us/ redirects to /about-us. But when I enter /school/ I get a 404 error. According to this https://github.com/angular-ui/ui-router/wiki/url-routing

'/user/:id' - Matches '/user/bob' or '/user/1234!!!' or even '/user/' but not '/user' or '/user/bob/details'. The second path segment will be captured as the parameter 'id'

So I am guessing it goes to the /school/:id state, note in such a case, $urlRouterProvider.rule is not called. Some sample defined modules

.config(function($stateProvider) {
    'ngInject';
    $stateProvider
        .state('school', {
    hasLefSideMenu: true,

            url: '/school/:id',
            templateUrl: '/school/school.html',
            controller: 'SchoolController',
            reloadOnSearch: false,
            controllerAs: 'schoolCtrl'
        });
})



.config(function($stateProvider) {
'ngInject';

$stateProvider
  .state('all-school', {
    hasLefSideMenu: true,

    url: '/school',
    templateUrl: '/all-schools.html',
    controller: 'allSchoolsController',
    controllerAs: 'allSchoolsCtrl'
  });

})

Ideally for all urls trailing slash should be removed. Any help would be great

Upvotes: 1

Views: 2618

Answers (1)

nikjohn
nikjohn

Reputation: 21850

You could use

$urlMatcherFactoryProvider.strictMode(false)

described here

Upvotes: 1

Related Questions