2017-08-09 67 views
0

我定義了諸如以下我的路線:Angular2混編版網址獲取當前url

const appRoutes: Routes = [ 
{ 
    path: 'auth', 
    component: AuthenticationComponent, 
}, 
{ 
    path: '', 
    component: HomeComponent, 
    canActivate:[AuthenticationGuard], 
    children:[ 
    { 
    path: 'list', 
    component: TaskListComponent, 
    canActivate:[AuthenticationGuard] 
    }, 
    { 
    path: 'create', 
    component: CreateTaskComponent, 
    canActivate:[AuthenticationGuard] 
    }, 
    { 
    path: 'profile', 
    component: ProfileComponent, 
    canActivate:[AuthenticationGuard] 
    }, 
    { 
    path: 'agreement', 
    component: UserAgreementComponent, 
    canActivate:[AuthenticationGuard] 
    }, 
    ] 

}, 

]; 

我瀏覽他們喜歡以下:

<nav class="mdl-navigation"> 
    <a class="mdl-navigation__link" href="#/list">List</a> 
    <a class="mdl-navigation__link" href="#/create">Create</a> 
    <a class="mdl-navigation__link" href="#/profile">Profile <span *ngIf="profileNotPresent" mdl-badge="Start"></span> </a> 
    <button class="mdl-button mdl-js-button" (click)="logout()"> 
     <i class="material-icons">exit_to_app</i> 
    </button> 
</nav> 

我不得不添加哈希,因爲當我部署的應用程序它開始拋出我的路線404錯誤。隨着哈希網址它的作品。

但是在我的代碼我有我在那裏顯示的條件下,是真實的,如果它是基本路線股利的條件:

if(this.router.url == '/'){ 
    this.showHomeContent=true; 
} 

那個時候沒有哈希我的網址是「/」,「/配置文件'等,它用來正確工作。現在他們是'#','#/ profile'等等,並且這個條件不再起作用,導致特定的div始終保持打開狀態。

我該如何解決這個問題?

+0

只是添加散列工作? '==#/' – DeborahK

回答

1

您需要開始使用Angular路由器進行導航。我的意思是[routerLink]而不是href。如果沒有#,你可能會得到404,如果你輸入一個URL試圖找到一個未知的資源。默認情況下,Angular使用PathLocationStrategy,在這種情況下發出服務器請求。

如果您要使用路由器導航,您可以通過配置重定向到index.html來解決此問題,然後路由器將正確導航。

因此,開始正常使用的路由器,而且您的應用模塊中添加此:

providers:[{provide: LocationStrategy, useClass: HashLocationStrategy}] 

路由器將被添加#-sign的網址,並不會作出導致服務器端請求404.但是,再次使用routerLink指令替換你的hrefs。

+0

我同意這一點,在角度應用程序內導航時,使用'routerLink'是必須的。 – Zze

0

它在文檔還挺解釋 - 如果使用PathLocationStrategy您必須提供APP_BASE_HREF或在您的index.html插入PathLocationStrategy

路由器支持兩種策略PathLocationStrategyHashLocationStrategy

領導<base href="/">

這應該解決您的問題。