Angular2 @ angular / router 3.0.0-alpha.3 - 如何在路由更改时获取路由名称或路径

时间:2016-06-18 15:00:17

标签: angularjs angular angular2-routing

我正在尝试在路由更改时获取app.component中的当前路由名称或路由路径,以便我可以将路由名称用作包装器div周围的页面类。我正试图找出解决这个问题的最佳方法。以前我订阅了路由器更改属性,就像我在下面列出的那样,但似乎不再提供@ angular / router 3.0.0-alpha.3。如果有人有任何想法或建议,我将非常感激。

{{1}}

2 个答案:

答案 0 :(得分:7)

史蒂夫的答案是当前记录的答案,但ActivatedRoute上的网址可观察到的并不是为我开除,除非我第一次点击基本网址(例如:从/ index转到/ index / item)工作,但从/ index / item到index / item / 2,index / dashboard,甚至/ index都没有)。

我不确定以下解决方案是否是最佳做法,性能影响是什么,但我能够在路由器的NavigationEnd事件中获得活动路由,其中​​包含以下内容: / p>

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ROUTER_DIRECTIVES, Router, NavigationEnd } from '@angular/router';

@Component({
    selector: 'navbar',
    directives: [ROUTER_DIRECTIVES], 
    template: `
                ...
              `    
})

export class NavBarComponent implements OnInit, OnDestroy {
    private sub: any;

    constructor(private router: Router) {
    }

    ngOnInit() {
        this.sub = this.router.events.subscribe(e => {
            if (e instanceof NavigationEnd) {
                console.log(e.url);
            } 
        });
    }


    ngOnDestroy() {
        this.sub.unsubscribe();
    }
}

无论您在网址树中的深度或导航到/从的位置,每次更改路径时都会触发此操作。

答案 1 :(得分:0)

这可能有所帮助,

import { CanActivate, Router, RouterStateSnapshot } from '@angular/router';

@Component({
  selector: 'my-component',
  templateUrl: 'my-component.html'
})
export class MyComponent implements CanActivate {
  constructor(private router: Router) {}

  canActivate(state: RouterStateSnapshot) {
   // this is the future route you are intended to visit
   console.log(state.url);
  }
}

https://angular.io/docs/ts/latest/guide/router.html

的更多详情