11

How do I get active route data like params inside the subscribed router.events?

I do not want to subscribe to 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

My question is different because I do not ask how to react to router events!

I ask for how to get the activate route params within the router.events !

Thats a difference for sure!

Pascal
  • 12,265
  • 25
  • 103
  • 195

3 Answers3

7
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);
});
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
3

Try this:

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

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

This injects the current active route, and latter you can get info from that route.

Darian Serrano
  • 203
  • 2
  • 3
3
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 => {})
Rusty Rob
  • 16,489
  • 8
  • 100
  • 116