1

This is a follow up to Angular 2.0 router not working on reloading the browser Even if I configure the router to use the HashLocationStrategy I still get the url paths without #. I follow exactly the Angular2 docs https://angular.io/docs/ts/latest/tutorial/toh-pt5.html and set the location strategy as described here https://angular.io/docs/ts/latest/guide/router.html

My bootstrap:

import {bootstrap}    from 'angular2/platform/browser';
import {provide} from 'angular2/core';
import {
    ROUTER_PROVIDERS,
    LocationStrategy,
    HashLocationStrategy
} from 'angular2/router';

import {AppComponent} from './app.component';

bootstrap(AppComponent, [
    ROUTER_PROVIDERS,
    provide(LocationStrategy, { useClass: HashLocationStrategy })
]);

And the router config:

@RouteConfig([
    {
        path: '/detail/:id',
        name: 'HeroDetail',
        component: HeroDetailComponent
    },
    {
        path: '/heroes',
        name: 'Heroes',
        component: HeroesComponent
    },
    {
        path: '/dashboard',
        name: 'Dashboard',
        component: DashboardComponent,
        useAsDefault: true
    }
])

I'd expect to see a url like http://localhost/#/dashboard in the browser, but I get http://localhost/dashboard. What am I missing?

Community
  • 1
  • 1
Gregor
  • 2,917
  • 5
  • 28
  • 50

4 Answers4

1

Try to move the ROUTER_PROVIDER and provide(..)-stuff into your app.component.ts file.

In there you should paste it into the @Component.providers-Array.

For a more detailed answer have a look at this post, it solved my problem which seems to be close to yours: https://stackoverflow.com/a/35879541/4977476

Community
  • 1
  • 1
SilverJan
  • 434
  • 5
  • 16
  • Thanks! Indeed! The problem is the definition of the LocationStrategy. It has to go to the providers array, rather then into the bootstrap. – Gregor Apr 04 '16 at 06:42
0

My understanding (which might be wrong, I am just beginning with Angular2) is that the useAsDefault acts as a redirect. But this isn't needed when using hash locations, since from the server's point of view, all pages are on '/' anyway.

manuBriot
  • 2,755
  • 13
  • 21
0

The problem seems to be, that the LocationStrategy has to be defined within the providers array, as pointed out by SilverJan and KochFolie. See HashLocationStrategy not working as expected

Community
  • 1
  • 1
Gregor
  • 2,917
  • 5
  • 28
  • 50
0

it's works for me:

...

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

import {
  APP_BASE_HREF,
  LocationStrategy,
  HashLocationStrategy
} from '@angular/common';


...

const appRoutes: Routes = [
  { path: '', loadChildren: './user-profile/user-profile.module#UserProfileModule'},
  ...
];

@NgModule({
 ...
  providers: [ { provide: APP_BASE_HREF, useValue: "/core/user" }, {provide: LocationStrategy, useClass: HashLocationStrategy}],
  bootstrap: [AppComponent]
})
export class AppModule { }