Sure, you can use it like this:
- You can listen to
events
Observable on the Router
instance.
- It is going to fire with a lot of events. So you might want to filter out the unnecessary events and only use the event type that you're interested in, i.e.
NavigationEnd
. You can achieve it using Rxjs's filter
operator.
- On subscribing to
NavigationEnd
, you will get an event object which would be of type NavigationEnd
. This has properties like urlAfterRedirects
and url
that you can leverage to understand if the routing action resulted in navigation to a particular component.
- In case of a refresh/reload, the
NavigationEnd
event won't fire. So if that fires, you can be sure that it was a situation of a page being routed into.
Something along the lines of this:
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router, NavigationEnd } from '@angular/router';
import { filter } from 'rxjs/operators';
@Component({...})
export class YourComponent implements OnInit {
constructor(
..., private router: Router, ...
) { }
ngOnInit() {
...
this.router.events
.pipe(
filter(event => event instanceof NavigationEnd)
)
.subscribe((event: NavigationEnd) => {
console.log('Got the Event URL as ', event.url);
if(event.urlAfterRedirects.includes('project')) {
console.log('This was redirected to the Project Component');
}
});
...
}
...
}
Here's a Sample StackBlitz for your ref.
PS: To confirm on the 4th point, just try pressing the reload button on the StackBlitz's View Mode and then check if anything gets printed on the console. Since this a reload, nothing will get printed. This can be considered as a certainty for a refresh/reload situation.