Reputation: 95
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() {}
}
Upvotes: 2
Views: 4086
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.
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.
Have the parent component listen to the router event, update a behaviorSubject and pass it to the child as input.
Upvotes: 1
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