2015-12-27 19 views
12

location.path()で/ about、/、/ newsのような現在のルートのパスを取得できます。 しかし、代わりにエイリアスを取得するにはどうすればいいですか?Angular2は現在のルートのエイリアスを取得します

{ path: '/about', as: 'About', component: About } 

可能ですか?

+0

を使用して

routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void { console.log(curr.stringifiedUrlSegments); } 

またはフルパスの相対的なルートを得ることができますか? –

+3

最終的にパスがローカライズされるためです。 私は実際には – Pietrzm

答えて

2

のエイリアスを渡すためにRouteDataを使用することです。私はあなたがルータからとしてを得る方法がわからない

this.router.currentInstruction.component.routeName 

:あなたとコンポーネントの名前を得ることができ、より

constructor(public router: Router) 

:あなたのコンポーネントで

、とコンストラクタでそれを注入config。しかしRouterLinkディレクティブで始まるする権利スポットのようになります。 https://angular.io/docs/ts/latest/api/router/RouterLink-directive.html

+1

にあるページを確認するのにエイリアスを使うのが良いと思ったが、なぜ 'location.path()'を使わないのだろうか? –

+1

ハッシュ戦略がある場合、location.pathは機能しません。 url /#/ aboutは 'about'ではなく '/'を返します –

+0

ルータの最新の反復には 'currentInstruction'が含まれていません。 –

0

あなたが可能なエイリアスのリストを知っている場合、それはrouter.generateroute.isActiveRouteの組み合わせを使用して、現在のエイリアスの名前を見つけることが可能です:

のためにたとえば、私は3つのステップでウィザードを持っています。私は、配列内のステップの別名のリストを持っている:

const alias = this.wizardAliases 
    .map(alias => ({ alias, navigationInstruction: this.router.generate([alias]) })) 
    .filter(x => this.router.isRouteActive(x.navigationInstruction)) 
    .map(x => x.alias); 

if (alias.length === 1) { 
    console.log(`alias is ${alias}`); 
} 

免責事項:

private wizardAliases = [ 
    'wizardStep1', 
    'wizardStep2', 
    'wizardStep3' 
]; 

私は、現在のエイリアス名を決定するために、次のコードを使用して、私はこの作品かどうかを確認するためにしようとしていませんルートパラメータを使用します。

3

注:以下は2.0ベータシリーズでテストされています。 RCバージョンには、変更が加えられた更新されたルータコンポーネントがあります。古いものはrouter-deprecatedに改名されました。これはまだ新しいルータに対してテストされていません。

以下は、アクティブルートに応じてFooまたはBarと表示されます。 > = Angular2 RC.xについては

@Component({ 
    selector: 'app', 
    templateUrl: 'app/app.html', 
    directives: [ROUTER_DIRECTIVES] 
}) 
@RouteConfig([ 
    {path:'/', name: 'Foo', component: FooComponent, useAsDefault: true}, 
    {path:'/bar', name: 'Bar', component: BarComponent, useAsDefault: false}, 
]) 
export class AppComponent implements OnInit { 
    constructor(private _router: Router) { 
    } 

    ngOnInit() { 
     console.log('current route name', 
        this._router.currentInstruction.component.routeName); 
    } 
} 
+1

サブコンポーネントの中にあるときは、あなたが知りたいルートに応じて、 'this._router.root.currentInstruction.component.routeName'(注_root_)を使うことができます。 – ZoolWay

1

(新しいルータ)

は新しいルータにはもう何のエイリアスはありません。

ローカルコンポーネントエイリアスを取得したい理由

constructor(private router:Router) {} 

    routerOnActivate(curr:RouteSegment, prev?:RouteSegment, currTree?:RouteTree, prevTree?:RouteTree):void { 
    console.log(this.router.serializeUrl(tree)); 
    } 

または

constructor(router:Router, private location:Location) { 
    router.changes.subscribe(() => { 
    console.log(this.location.path()); 
    }); 
} 
+0

参照http://stackoverflow.com/questions/37183874/get-the-path-or-the-name-of-the-routes-in-angular-2/37207316#37207316 –

関連する問題