2

I am currently working on an Angular2 Project using TypeScript and I can't get the HashLocationStrategy to work. I override the LocationStrategy in the bootstrapping the way it is explained here: https://angular.io/docs/ts/latest/guide/router.html

import {bootstrap}         from 'angular2/platform/browser';
import {ROUTER_PROVIDERS}  from 'angular2/router';
import {AppComponent}      from './app.component';
// Add these symbols to override the `LocationStrategy`
import {provide}           from 'angular2/core';
import {LocationStrategy,
        HashLocationStrategy} from 'angular2/router';
bootstrap(AppComponent, [
  ROUTER_PROVIDERS,
  provide(LocationStrategy,
         {useClass: HashLocationStrategy})
]);

I have created a plunker to demonstrate my Problem here: https://plnkr.co/edit/YE5w4iky53SHRi211lqX?p=preview

Has anybody else encountered this issue? Have I misunderstood this or am I missing something?

Edit: The expected result would be that the routing uses hashes in the URL. In the example that should produce an url like this: .../#/fubar, instead I get .../fubar

To see the generated urls, you will have to run the plunker in a separate window (blue full screen button)

Richard Naeve
  • 23
  • 1
  • 5

2 Answers2

4

The example doesn't follow the recommended best practices of splitting the files for bootstrap- and app-code, and is a bit confusing, in my eyes.

It works fine if you move the HashLocation-code into your app.component file:

app.ts

import [..]

@Component({
    [..]
    providers:[
        ROUTER_PROVIDERS,
        provide(LocationStrategy, {useClass: HashLocationStrategy})]
})
@RouteConfig([..])
    export class App{
        [..]
    }

boot.ts

import [..]
[..]
bootstrap(App);

Take a look at my working fork of your plunker:
https://plnkr.co/edit/TNr8jQjiVmhADhWzbRsC?p=preview

I'm just guessing, but the reason might be, that you overwrite the "providers" attribute in the AppComponent, as shown in the examples.

KochFolie
  • 316
  • 3
  • 4
2

The question and answer are based on beta version of angular 2. Here is a working example Angular 2.3: from official docs https://angular.io/docs/ts/latest/guide/router.html#!#browser-url-styles

import { NgModule }             from '@angular/core';
import { BrowserModule }        from '@angular/platform-browser';
import { FormsModule }          from '@angular/forms';
import { Routes, RouterModule } from '@angular/router';

import { AppComponent }          from './app.component';
import { PageNotFoundComponent } from './not-found.component';

const routes: Routes = [

];

@NgModule({
  imports: [
    BrowserModule,
    FormsModule,
    RouterModule.forRoot(routes, { useHash: true })  // .../#/crisis-center/
  ],
  declarations: [
    AppComponent,
    PageNotFoundComponent
  ],
  providers: [

  ],
  bootstrap: [ AppComponent ]
})
export class AppModule { }
David Dehghan
  • 22,159
  • 10
  • 107
  • 95