Angular2 keep/add trailing slash

2019-07-07 06:07发布

问题:

I have an issue with trailing slashes being removed by Angular2. I've setup my dotnet core application to add them, but they get removed as soon as the js get loaded in.

Is it even possible in Angular2?

(My client requires it, so no need to add a comment saying; don't use trailing slash).

Thanks in advance.

EDIT: Should have added, this is running with Angular2-Universal, so upgrading the angular version is not that easy :(

回答1:

We have a website by Angular one, after we decided migrating to Angular4 Universal one of our problem was auto-removed trailing slash that efficacy on our site SEO, after many tries we found a hacky way for preventing this unvaluable action by same as below code(in app.module.ts file):

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

import {AppComponent} from './app.component';


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


Location.stripTrailingSlash = UnstripTrailingSlashLocation.stripTrailingSlash;

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [...],
  providers: [...],
  bootstrap: [AppComponent]
})
export class AppModule {
}


回答2:

I believe is a problem faced by .Net Devs

The commit with this fix in the 2.3.0-beta.1 version of angular. Try changing your angular version and see if the problem is fixed.

fix: support trailing slash in basePath

Alternatively

Have you tried this? This seems to do the trick on my machine

In app.routing.ts:

{ path: 'link/.', component: MyComponent },

A hyperlink:

<li class="nav-item" [routerLinkActive]="['active']" [routerLinkActiveOptions]="{exact:true}">
        <a class="nav-link" [routerLink]="['/link/.']">MyComponent</a>
    </li>