Angular:一些路由使用PathLocationStrategy,但其他一些路由使用HashLocationStrategy

时间:2017-08-04 15:10:34

标签: angular angular2-routing angular2-services angular-routing angular-router

我的app.routes中有4条路线。

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';

export const pageRoutes: Routes = [
  {path: '', redirectTo: 'home', pathMatch: 'full'},
  {path: 'home', component: HomeComponent},
  {path: 'transaction', loadChildren: './app/transaction.module#TransactionModule'},
  {path: 'evidence', loadChildren: './app/evidence.module#EvidenceModule'}
];

@NgModule({
  imports: [RouterModule.forRoot(pageRoutes)],
  exports: [RouterModule],
})
export class AppRoutingModule {}

在app.routes中,我没有对LocationStrategy进行任何具体设置。因为对于transaction路由,我想使用angular2默认的PathLocationStrategy,它不允许用户刷新页面。

但对于evidence路由,我实际上希望用户能够刷新页面。所以我想在这里使用HashLocationStrategy。

这是evidence-routing.module

    @NgModule({

          imports: [RouterModule.forChild([
            {path:':sessionId', component: EvidenceComponent}
            { path: '**', redirectTo: '/404' },
            { path: '404', component: PageNotFoundComponent}
          ])], 
          exports: [RouterModule],
          providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]

    })
    export class EvidenceRoutingModule {}

我想在providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }]中添加evidence-routing.module以启用HashLocationStrategy并仅应用于此路由。

但是一旦我把它放在那里,整个应用程序将采用HashLocationStrategy,它也适用于事务路由。

我找不到任何好的解决方案来处理这个问题。

有关此问题的任何建议吗?

非常感谢!

1 个答案:

答案 0 :(得分:2)

您不能为不同的路由使用不同的LocationStrategy,此设置适用于Router,而不适用于路由,并且一个应用程序只能有一个路由器。

您应该确保正确配置服务器,然后即使使用PathLocationStrategy,重新加载也适用于所有路由。

确保您的服务器配置为支持HTML5 pushState 这只是意味着服务器返回index.html以获取对未知资源的请求。

相关问题