2016-08-24 36 views
3

我正在開發一個項目,我需要兩種GUI語言。我有LangService爲每個組件提供短語。每個組件根據當前路線獲取活動語言並從LangService請求短語。在路線中更改參數

我的問題是......我需要在我的導航欄內有「我的語言切換」,這是在主要的「app.component」中。 Navbar始終位於頂部,所以我可以從每個組件訪問它。我希望能夠點擊導航欄中的按鈕並更改當前路線(更改當前語言)。這怎麼可能? 我認爲有一種方法可以改變route.params。那樣我會改變route.params['lang'] = 'EN';

AppComponent.html:

<nav class="navbar navbar-default"> 
    <div class="container-fluid"> 
    <div class="navbar-header"> 
     <a class="navbar-brand" href="#">{{ title }}</a> 
    </div> 
    <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1"> 
     <ul class="nav navbar-nav navbar-right"> 
     <ol class="breadcrumb"> 
      <li *ngFor="let lang of langs"><a (click)="changeLanguage()">{{ lang }}</a></li> 
     </ol> 
     </ul> 
    </div> 
    </div> 
</nav> 
<router-outlet></router-outlet> 

AppComponent.ts(我怎麼覺得這是可行的):

export class AppComponent { 
    changeLanguage() { 
    // catch the route params lang 
    // change route params 
    // set new route 
    } 
} 

回答

2

使用導航導航到相同的路線有不同的參數。因此,如果您位於/ component/subroute/en並切換到西班牙語,請使用router.navigate,其路徑爲/ component/subroute/es。

路由文檔(https://angular.io/docs/ts/latest/guide/router.html#!#route-parameters)包含一個用於監聽更改路由參數的示例,您將需要執行此操作,因爲組件不會重新加載,因爲實際路由不會更改,而只是參數。