2016-03-04 147 views
2

我目前正在使用TypeScript处理Angular2项目,并且无法让HashLocationStrategy工作。我重写LocationStrategy在引导它在这里解释道:我创建了一个plunker来证明我的问题就在这里https://angular.io/docs/ts/latest/guide/router.htmlHashLocationStrategy不按预期方式工作

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}) 
]); 

https://plnkr.co/edit/YE5w4iky53SHRi211lqX?p=preview

有其他人遇到这个问题?我误解了这个还是错过了一些东西?

编辑:预期的结果是路由在URL中使用散列。在应该产生这样一个网址的例子中:... /#/ fubar,而是我得到.../fubar

要查看生成的url,必须在单独的窗口中运行plunker全屏按钮)

+1

什么是“不能让......上班”呢?什么是预期的行为?什么是实际行为?任何错误消息? –

+1

对我来说,你的plunkr工作。我唯一的评论是,你在引导程序和组件中定义了两次'ROUTER_PROVIDERS' ... –

回答

4

该示例不遵循分离引导程序和应用程序代码的文件的推荐最佳实践,并且在我眼中有点混乱。

如果移动HashLocation代码到您的app.component文件,它工作正常:

app.ts

import [..] 

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

boot.ts

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

取看看我的擒纵器的工作叉:
https://plnkr.co/edit/TNr8jQjiVmhADhWzbRsC?p=preview

我只是在猜测,但其原因可能是,您覆盖AppComponent中的“providers”属性,如示例中所示。

+1

绝对正确。问题是覆盖ROUTER_PROVIDERS。谢谢。 –

2

的问题和答案是基于对角2.这里测试版的工作示例角2.3:从官方的文档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 { }