如何在app.component中获取活动路由

时间:2016-10-13 04:35:19

标签: angular

我想在app.component中获取活动路线,这样我就可以在我的应用标题中隐藏一些元素。

例如,如果路由/资产,

我设置了isHeader: boolean = true;

当我这样做时,我得到一个对象:

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

 constructor(router: ActivatedRoute) {
   this.route = router.url;
   console.log(this.route);
}

我如何获得路线价值/资产?

1 个答案:

答案 0 :(得分:2)

你必须"听"到路由器事件。

请参阅我的plunker了解工作演示:https://plnkr.co/edit/XJmOa7rmtvBpuJDfQ2Vd?p=preview

有趣的部分是这段代码:

@Component({
  selector: 'my-app',
  template: `
    <div>
      <h2>Hello {{name}}</h2>
    </div>
    <a routerLink="/cmp1">cmp1</a><br />
    <a routerLink="/cmp2">cmp2</a><br />
    <a routerLink="/cmp3">cmp3</a><br />

    <router-outlet></router-outlet>
  `,
})
export class App {
  name:string;
  constructor(private _r: Router) {
    this.name = 'Angular2'

    this._r.events.subscribe(event => {
      if (event instanceof RoutesRecognized) {
        console.log('navigated to:', event.url);
        console.log('route state', event.state);
        console.log('');
      }
      else if (event instanceof NavigationEnd) {
        // if u dont need the state, you could even use this event-type..
      }
    });
  }
}

订阅路由器事件并检查触发了哪种类型的事件。 如果你想使用state(params,queryParams,...),我建议使用RoutesRecognized - event-type。但如果你只想获得当前NavigationEnd,你甚至可以使用url - 事件类型。