YSFKBDY
YSFKBDY

Reputation: 896

Detecting difference with route change and url entry

I've tried to find but couldn't, so here I am. I wanna learn that if is there any way to detect difference between route change and url entry. I have some scenarios needs to respond differently to route change and url entry - like clicking the link from bookmarks.

Upvotes: 0

Views: 378

Answers (1)

YSFKBDY
YSFKBDY

Reputation: 896

I wrote something like this in my app.component, and it works as intended:

changeCount = 0;

constructor(private router: Router) {
    this.subs.add(this.router.events.subscribe((event: Event) => {
      if (event instanceof NavigationEnd) {
        this.changeCount++;

        if (this.changeCount == 1) {
            // do some works
        } else {
            // do some other works
        }
      }

      if (event instanceof NavigationError) {
        this.router.navigateByUrl("/");
      }
    }));
}

If changeCount equals to 1, that means this is the first entry to website, and if it is greater than 1, then it means this is a route change.

Upvotes: 1

Related Questions