2016-08-04 3 views
6

app.component.htmlテンプレートにルートの名前を表示したいとします。角2、現在のルート名を表示する方法は? (ルータ3.0.0-beta.1)

{{router.currentRoute.name}} 

私の現在のルータの設定:あなたのルートは、データプロパティに自分のルート名で構成されている場合

export const routes: RouterConfig = [ 
    { 
     path: '', 
     redirectTo: '/catalog', 
     pathMatch: 'full' 
    }, 
    { 
     path: 'catalog', 
     name: 'Catalog', // Is this property deprecated? 
     component: CatalogComponent 
    }, 
    { 
     path: 'summary', 
     name: 'Summary', 
     component: SummaryComponent 
    } 
]; 
+1

新しいルータにルート名はありません。 –

+0

ルート名を表示する場合は、私自身のソリューションをコーディングする必要がありますか? –

+0

これに 'data'パラメータを使うことができます。 https://angular.io/docs/ts/latest/api/router/index/RouterConfig-type-alias.html –

答えて

14

のような私は簡単な解決策、次のように書くことができる何かを探していますこの:あなたのapp.component.tsあなたがimport 'rxjs/add/operator/filter'; + import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';と、次のことができないで

{ 
    path: 'somepath', 
    component: SomeComponent, 
    data: { 
     name: 'My Route Name' 
    } 
} 

constructor(
    private route: ActivatedRoute, 
    private router: Router 
) { } 

ngOnInit() { 
    this.router.events 
    .filter(event => event instanceof NavigationEnd) 
    .subscribe(event => { 
     let currentRoute = this.route.root; 
     while (currentRoute.children[0] !== undefined) { 
     currentRoute = currentRoute.children[0]; 
     } 
     console.log(currentRoute.snapshot.data); 
    }) 
} 

これはNavigationEndイベントをリッスンして、あなたはそのルートのdataにアクセスできるように、現在のルートまで横断します。

上記のコードを使用して/somepageにいる場合は、コンソールに{ name="My Route Name"}と表示されます。

+0

ありがとう! –

+0

'TypeError:this.router.events.filterは関数ではありません。 ' – Matiishyn

+0

' filter'関数を 'rxjs'から' import'するのを忘れないでください。 –

関連する問題