mishoo78
mishoo78

Reputation: 95

Angular 4 router.events don't seem to trigger RoutesRecognized event for the first time the user navigates

This is a simple ts code that tests router triggered events

import { Component, OnInit } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';

@Component({
  selector: 'user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
  })
export class UserComponent implements OnInit {

	constructor(private router: Router) {
		this.router.events.subscribe((e)=>{console.log(e)})
	}

	ngOnInit() {}
}
The only event that is triggered is NavigationEnd. Where do i catch the rest of the events?

Upvotes: 2

Views: 4086

Answers (2)

Bo Li
Bo Li

Reputation: 11

misutkame, I hope this is not too late, I've encountered the same problem. I believe it is due to Router event being triggered before the component's life cycle began. Thus what you are asking cannot be directly addressed. There are several ways to work around it though.

  1. Use a snapshot of the activated route during the child component's creation. This way you'll get router data that is required by your logic during the component's life cycle. You'll still need to set up a listener for later events.

  2. Have the parent component listen to the router event, update a behaviorSubject and pass it to the child as input.

Upvotes: 1

Nawrez
Nawrez

Reputation: 3332

try to use RoutesRecognized:

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


ngOnInit() {
    this.router.events
      .filter((e: any) => e instanceof RoutesRecognized)
      .pairwise()
      .subscribe((e: any) => {
        console.log(e);
      });
  }

Upvotes: 0

Related Questions