7

I have to find whether a page is refreshed or it is loaded because of some routing.

I think it's possible using Angular Router's NavigationEnd event by subscribeing to the router events.

Anyone knows how to do it?

No pure javascript solutions, please.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
Janier
  • 3,982
  • 9
  • 43
  • 96

2 Answers2

8

Sure, you can use it like this:

  1. You can listen to events Observable on the Router instance.
  2. 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.
  3. 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.
  4. 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.

SiddAjmera
  • 38,129
  • 5
  • 72
  • 110
1

In App.component.ts

subscription: Subscription;
pageReloading: boolean = false;

constructor(private router: Router){
    this.subscription = router.events.subscribe((event) => {
        if (event instanceof NavigationStart) {
          this.pageReloading = !router.navigated;
          console.log(this.pageReloading)
        }
    });
}
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Muthulakshmi M
  • 651
  • 7
  • 8