Angular2 – 带有HashLocationStrategy的APP_BASE_HREF

前端之家收集整理的这篇文章主要介绍了Angular2 – 带有HashLocationStrategy的APP_BASE_HREF前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个角度应用程序使用路由与HashLocationStrategy,我需要在主html文件中设置不同的值和路由不同.

我试过这个解决方案:

@NgModule({
    imports: [
        BrowserModule,FormsModule,HttpModule,MyRouting // with useHash set to true
    ],declarations: [
        AppComponent,],providers: [
        { provide: APP_BASE_HREF,useValue: '/prefix' }
    ],bootstrap: [AppComponent]
})
export class AppModule { }

工作得很好,但值’/ prefix’是在哈希后插入,如下所示:

http://myapp.com/#/prefix/home

我想要的是:

http://myapp.com/prefix/#/home

为清楚起见,我的基本标签是:

<base href="/">
@H_301_17@
@H_301_17@
我遇到了同样的问题并用我自己的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;
    }
}

然后在我的模块中使用它

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 })
    ],useValue: window.location.pathname },{ provide: LocationStrategy,useClass: CustomLocationStrategy },]
})
export class AppModule {
}
@H_301_17@ 原文链接:https://www.f2er.com/angularjs/143711.html

猜你在找的Angularjs相关文章