我正在尝试创建一个具有哈希位置策略的应用程序,但它不会将哈希添加到 url。例如,当我单击与 { path: ‘/polls’, name: ‘Polls’, component: PollsComponent } 关联的按钮时,它会加载具有以下 url 的页面:localhost:3000/polls。
我必须更改什么才能获得哈希位置策略?如果我想使用哈希定位策略,为什么我必须设置默认的基本 url?
这是 app.component.ts 中定义所有路由的路由:
import {Component} from 'angular2/core'
import {HTTP_PROVIDERS, Http} from 'angular2/http';
import 'rxjs/Rx'; // load the full rxjs
import {ROUTER_PROVIDERS, RouteConfig , ROUTER_DIRECTIVES} from 'angular2/router';
import { ResultsComponent } from './results/results.component'
import { VotingCardsComponent } from './votingcards/votingcards.component'
import { DashBoardComponent } from './dash/dash.component'
import { PollsComponent } from './pollslist/pollslist.component'
@Component({
selector: 'my-app',
templateUrl: 'app/app.component.html',
directives: [ROUTER_DIRECTIVES, ResultsComponent, VotingCardsComponent, DashBoardComponent],
providers: [HTTP_PROVIDERS,
ROUTER_PROVIDERS]
})
@RouteConfig([
{ path: '/vote', name: 'VotePage', component: VotingCardsComponent },
{ path: '/votepoll/:id', name: 'VotePoll', component: VotingCardsComponent },
{ path: '/results', name: 'Results', component: ResultsComponent },
{ path: '/polls', name: 'Polls', component: PollsComponent },
{ path: '/', name: 'DashBoard', component: DashBoardComponent, useAsDefault: true }
])
export class AppComponent { }
这是我的 main.ts,我在其中配置基本 url:
import {bootstrap} from 'angular2/platform/browser';
import {AppComponent} from './app.component';
//this is to avoid the href empty issue
import {provide} from 'angular2/core';
import {APP_BASE_HREF, ROUTER_PROVIDERS} from 'angular2/router';
bootstrap(AppComponent, [
//this is to avoid the href empty issue
ROUTER_PROVIDERS,
provide(LocationStrategy, { useClass: HashLocationStrategy }),
provide(APP_BASE_HREF, { useValue: '/' })
]);
原文由 Diego Unanue 发布,翻译遵循 CC BY-SA 4.0 许可协议
ROUTER_PROVIDERS
不应 添加到子组件,只 为了
或者 只是
HTTP_PROVIDERS
在我看来也更适合根组件或bootstrap()
但将它们添加到其他地方不会破坏任何东西。(另请参阅 角度 2 和 IIS 的路由错误)