Angular2 - 带有 HashLocationStrategy 的 APP_BASE_HREF [英] Angular2 - APP_BASE_HREF with HashLocationStrategy

查看:23
本文介绍了Angular2 - 带有 HashLocationStrategy 的 APP_BASE_HREF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Angular 应用程序使用带有 HashLocationStrategy 的路由,我需要在主 html 文件中设置不同的值,并在路由中设置不同的值.

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 solution:

@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' 在哈希后插入,如下所示:

Works almost well but value '/prefix' is insert after hash, like this:

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

而我想要:

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

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

For clarity, my base tag is:

<base href="/">

推荐答案

我遇到了同样的问题,并用我自己的 HashLocationStrategy 子类修复了它

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

这篇关于Angular2 - 带有 HashLocationStrategy 的 APP_BASE_HREF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆