Angular: Some routes use PathLocationStrategy but some other routes use HashLocationStrategy

ぐ巨炮叔叔 提交于 2019-12-23 02:25:08

问题


I have 4 routes in my app.routes.

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

In the app.routes, I didn't do any specific setup for LocationStrategy. Since for the transaction route, I want to use the angular2 default PathLocationStrategy, which doesn't allow the user to refresh the page.

But for the evidence route, I actually want the users to be able to refresh the page. So I'd like to use HashLocationStrategy here.

This is the 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 {}

I wanted to add providers: [{ provide: LocationStrategy, useClass: HashLocationStrategy }] inside evidence-routing.module to enable HashLocationStrategy and only apply to this route.

But once I put it there, the entire application will adopt the HashLocationStrategy, it also works for the transaction route.

I couldn't find any good solutions to handle this.

Any advice on this issue?

Many Thanks!


回答1:


You can't use a different LocationStrategy for different routes, this setting is for the Router, not for routes, and there can only be exactly one router for one application.

You should rather ensure the server is configured properly, then reload will work for all routes even with PathLocationStrategy.

Ensure your server is configured to support HTML5 pushState.
This just means that the server returns index.html for requests to unknown resources.



来源:https://stackoverflow.com/questions/45510207/angular-some-routes-use-pathlocationstrategy-but-some-other-routes-use-hashloca

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