2016-07-14 53 views
1

我有一個非常簡單的應用程序Angular2路由 - 手動網址導航

我app.component.html看起來是這樣的:

<a [routerLink]="['/Test']">CLICK ME</a> 
<div class="main-container"> 
    <router-outlet></router-outlet> 
</div> 

我app.component.ts看起來是這樣的:

@Component({ 
    selector: 'app', 
    templateUrl: 'app/app.component.html', 
    directives: [HomeComponent, TestComponent, ROUTER_DIRECTIVES] 
}) 

@RouteConfig([ 
    {path: '/', component: HomeComponent, as: 'HomeComponent'}, 
    {path: '/test', component: TestComponent, as: 'Test'} 
]) 

export class AppComponent { } 

導航到我的應用程序,我去

http://localhost/app 

這是完美的,它導航我到我的家庭組件視圖如預期。 當我點擊「按我」按鈕,我瀏覽到

http://localhost/app/test 

和預期的一樣我的測試組件呈現......但是,如果我手動導航到

http://localhost/app/test 

我家成分被加載而不是我的測試組件...什麼給了?我如何設置路由,以便手動導航到測試網址實際上在路由器插座中返回測試組件的視圖?這可能嗎?我不想去,每次登陸頁面...

+0

您是否在index.html中設置了您的基礎href?它應該像[文檔建議](https://angular.io/docs/ts/latest/guide/router.html#!#base-href)'' –

+0

什麼是你的angular2版本? –

+0

beta17,基礎href是好的,我有一個重新編寫規則自動服務/app/index.html,我認爲是需要獲得PathLocationStrategy工作...但它不...使用節點精簡版服務器 – Mames

回答

1

在新的路由器especification你需要的東西是這樣的:

router.navigateByUrl("/app"); 

router.navigate(['HomeComponent'], {relativeTo: route}); 
0

這可能是由於到服務器配置。對於上下文之後的任何錯誤路徑或路徑,您的服務器可能會重定向到index.html

您應該將服務器配置爲重寫路徑而不是重定向。

提供服務器上的代碼中使用了

+0

你是正確的,在我的服務器web.config我有 <條件logicalGrouping =」MatchAll「> <動作類型= 「重寫」 URL = 「/應用/ index.html中」/> 卸下此線和檢測 - 我現在我404刷新上的HTTP後://localhost/app/test鏈接 – Mames

+0

正如我所說的,你需要配置重寫路徑而不是重定向。你正在使用哪個服務器可能會幫助建議如何重寫 –

+0

對於Apache tomcat:https://tomcat.apache.org/ tomcat-8.0-doc/rewrite.html –

0

解決更多的信息和服務器 - 我的引導是缺少一些內容......我有

bootstrap(AppComponent, [ 
    ROUTER_BINDINGS, 
    bind(APP_BASE_HREF).toValue(location.pathname), 
    bind(LocationStrategy).toClass(PathLocationStrategy) 
    ]); 

然而,這是不正確的,手動輸入:

bootstrap(AppComponent, [ 
    ROUTER_BINDINGS, 
    bind(APP_BASE_HREF).toValue("/"), 
    bind(LocationStrategy).toClass(PathLocationStrategy) 
    ]); 

似乎工作。感謝大家的幫助!