HashLocationStrategy does not produce # locations when routing?

て烟熏妆下的殇ゞ 提交于 2019-12-05 04:00:46

I tried your code, it works

my code below:

boot.ts

import {bootstrap}    from 'angular2/platform/browser'
import {provide} from 'angular2/core';
import {AppComponent} from './app.component'
import {ROUTER_PROVIDERS, LocationStrategy, 
        HashLocationStrategy,
        PathLocationStrategy,
        APP_BASE_HREF, } from 'angular2/router'


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

-

app.ts

import {Component} from 'angular2/core';
import {RouteConfig, ROUTER_DIRECTIVES} from 'angular2/router';

@Component({
  selector:'second',
  template: `<h1>second</h1>`
})

export class SecondComponent{}

@Component({
   selector: 'home',
   template: `<h1>hello</h1>`
})

export class HomeComponent{}

@Component({
   directives : [ROUTER_DIRECTIVES],
   selector: 'my-app',
   template: 
    `<a [routerLink]="['Home']">home</a>
     <a [routerLink]="['Second']">Second</a>
     <router-outlet></router-outlet>
    `
})


 @RouteConfig([
   {path :'/' ,name: 'Home', component: HomeComponent},
   {path :'/second', name : 'Second', component : SecondComponent}

  ])

 export class AppComponent { }

I find your problem, delete this line

providers : [ROUTER_PROVIDERS]

the details I don't know why, maybe angular can't not process when you are using ROUTERPROVIDERS twice, looking forward someone can help u

As per Angular 2 final release you have to include LocationStrategy to use HashLocationStrategy class by putting it inside providers of main @NgModule by doing {provide: LocationStrategy, useClass: HashLocationStrategy}

app.module.ts

import {Component, NgModule} from '@angular/core';
import {
  LocationStrategy,
  HashLocationStrategy
} from '@angular/common';
@NgModule({
   imports: [...], //put module to import here
   declarations: [...], //put all component, pipe & directive
   exports: [...], //module to export
   //providers should reside here
   providers: [{provide: LocationStrategy, useClass: HashLocationStrategy}]
})
class AppModule {}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!