在router.events中获取活动路由数据

时间:2017-01-05 23:07:39

标签: angular typescript angular2-routing

如何获得订阅的router.events中的params等活动路由数据?

想要订阅this.route.params!

// Catch any events in a certain component, where I subscribe to it!
this.router.events.subscribe(event =>
{ 
// The event object has only the url (when is NavigationStart/End), there is nothing useful for me


});

更新

我的问题不同,因为我不问如何对路由器事件做出反应!

我问如何在router.events中获取激活路径参数!

肯定会有所不同!

3 个答案:

答案 0 :(得分:3)

试试这个:

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

@Component({
    ...
})
export class TestComponent implements OnInit{
    constructor(protected route: ActivatedRoute) {}
    ngOnInit() {
        let name = this.route.snapshot.params['name'];
    }
}

这将注入当前活动路由,后者可以从该路由获取信息。

答案 1 :(得分:2)

this.router.events.subscribe(event =>
{ 
  console.log(this.router.routerState.root);
  console.log(this.router.routerState.root.firstChild);
  console.log(this.router.routerState.root.firstChild && this.router.routerState.root.firstChild.firstChild);
});

答案 2 :(得分:0)

merge(of(this.route.snapshot.params), this.router.events.pipe(
      filter((event) => event instanceof NavigationEnd),
      map(() => this.route),
      map((route) => {
        while (route.firstChild) route = route.firstChild;
        return route;
      }),
      filter((route) => route.outlet === 'primary'),
      mergeMap(route => route.params),
    )).subscribe(p => {})