Angular中的哈希定位策略2

Die*_*nue 8 javascript angular2-routing angular

我正在尝试使用哈希位置策略创建应用程序,但它不会将哈希添加到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 { }
Run Code Online (Sandbox Code Playgroud)

这是我的主要配置我在哪里配置基本网址:

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: '/' })

]);
Run Code Online (Sandbox Code Playgroud)

小智 38

您可以在RouterModule.forRoot()中使用"useHash"选项.

RouterModule.forRoot(appRoutes, {useHash: true});
Run Code Online (Sandbox Code Playgroud)

https://discuss.atom.io/t/angular-2-routes-breaking-on-electron-app-refresh/28370/4

  • 这对我有帮助,因为这更适合Angular 2决赛(我在2.2.3).所有其他答案都适用于Angular 2的旧版本. (2认同)

Gün*_*uer 6

ROUTER_PROVIDERS应该不会被添加到子组件,

只有

providers: [ROUTER_PROVIDERS]
Run Code Online (Sandbox Code Playgroud)

可替代地

bootstrap(AppComponent, [ROUTER_PROVIDERS]);
Run Code Online (Sandbox Code Playgroud)

HTTP_PROVIDERS在我看来也更适合root组件,bootstrap()但它不会破坏任何东西以将其添加到其他地方.

(另请参阅使用角度2和IIS进行路由错误)


Luc*_*edo 5

一切正常,样本代码OP发布,与接受的答案中的内容一致.但作为次要注释,从RC.4开始,在引导程序文件中更改哈希位置策略所需的格式如下:

{ provide: LocationStrategy, useClass: HashLocationStrategy },
Run Code Online (Sandbox Code Playgroud)