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

问题描述 投票:5回答:3

如何获得订阅的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


});

UPDATE

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

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

这肯定是有区别的!

angular typescript angular2-routing
3个回答
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);
});

3
投票

试试这个:

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

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

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


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 => {})
© www.soinside.com 2019 - 2024. All rights reserved.