Angular 5: allow trailing slash in routes

I am updating an old website with Angular, and one of the requirements I need to fulfill is that all routes should remain the same as they are (for SEO purposes).

Many of the old website routes end with a slash (Like /my/route/), and some of them end with .html, for example /my/route.html.

The problem is that routerLink removes the final slash at each end of the route with a slash (my route now /my/route).

How can I do routerLinkto save a trailing slash?

Here's a quick example: AngularTrailingSlash .

+4
source share
3

app.module.ts

import {Location, PathLocationStrategy} from '@angular/common';


const _orig_prepareExternalUrl = PathLocationStrategy.prototype.prepareExternalUrl;

PathLocationStrategy.prototype.prepareExternalUrl = function(internal) {
  const url = _orig_prepareExternalUrl.call(this, internal);

  if (url === '') {
    return url;
  }

  console.log('For ' + internal + ' we generated ' + url);
  if (url.endsWith('.html')) {
      return url;
  }

  if (url.endsWith('/')) {
    return url;
  }


  return url + '/';

};

Location.stripTrailingSlash = function (url) {
    const /** @type {?} */ match = url.match(/#|\?|$/);
    const /** @type {?} */ pathEndIdx = match && match.index || url.length;
    const /** @type {?} */ droppedSlashIdx = pathEndIdx - (url[pathEndIdx - 1] === '/' ? 1 : 0);
    const first = url.slice(0, droppedSlashIdx);
    const last = url.slice(pathEndIdx);

    if (first.endsWith('.html')) {
        return first + last;
    }

    return first + '/' + last;

};

, .html

+1

main.ts, routerLink.

import { Location } from '@angular/common';
const __stripTrailingSlash = (Location as any).stripTrailingSlash;
(Location as any).stripTrailingSlash = function _stripTrailingSlash(url: string): string {
  return /[^\/]\/$/.test(url) ? url : __stripTrailingSlash(url);
}

// import main ng module
// bootstrap on document ready
0

Try with a location class to expand AppModuleas follows:

app.module.ts:

import { Injectable } from '@angular/core';
import { Location } from '@angular/common';

@Injectable()
export class UnstripTrailingSlashLocation extends Location {
  public static stripTrailingSlash(url: string): string {
    return url;
  }
}
Location.stripTrailingSlash = UnstripTrailingSlashLocation.stripTrailingSlash;

@NgModule({
            ...
0
source

Source: https://habr.com/ru/post/1692646/


All Articles