Angular2 - APP_BASE_HREF with HashLocationStrategy

 ̄綄美尐妖づ 提交于 2019-11-29 02:22:33
Volker Andres

I came across the same problem and fixed it with my own Subclass of HashLocationStrategy

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

@Injectable()    
export class CustomLocationStrategy extends HashLocationStrategy {
    prepareExternalUrl(internal: string): string {
        return this.getBaseHref() + '#' + internal;
    }
}

Then just using it in my module

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { LocationStrategy } from '@angular/common';
import { APP_BASE_HREF } from '@angular/common';
import { CustomLocationStrategy } from './app.common';

const appRoutes: Routes = [...];

@NgModule({
    imports: [
        RouterModule.forRoot(appRoutes, { useHash: true })
    ],
    providers: [
        { provide: APP_BASE_HREF, useValue: window.location.pathname },
        { provide: LocationStrategy, useClass: CustomLocationStrategy },
    ]
})
export class AppModule {
}

yahoooooooooooo !! got it to work.

in your index.html file, specify the baseurl as "." like this:

<base href=".">

and specify the hash location strategy in your providers property in your NgModule decorator in your app.module.ts, like this:

@NgModule({
  declarations: [AppComponent],
  imports: [
    FormsModule,
    HttpModule,
    AppRoutingModule,
    ShellModule,
    ShellProvidersModule,
    BrowserModule
  ],
  providers: [
    SessionService,
    { provide: LocationStrategy, useClass: HashLocationStrategy },
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

see: https://github.com/datumgeek/plotter-app-seed-angular2/blob/master/src/app/app.module.ts#L26

running demo here: https://datumgeek.github.io/plotter-app-seed-angular2/#/shell;stateRepositoryId=file-host-01;sessionId=session-03

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!