Angular2 - APP_BASE_HREF with HashLocationStrategy

后端 未结 2 938
广开言路
广开言路 2020-12-16 04:36

I have an angular application uses routing with HashLocationStrategy, I need to set different value in main html file and different in routing.

I tried this solutio

2条回答
  •  醉酒成梦
    2020-12-16 05:34

    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 {
    }
    

提交回复
热议问题