Tomas
Tomas

Reputation: 3436

Angular router - way to identify, does the router perform initial navigation or it comes from app

Hello Stack community.

As in question title, I'm wondering is there a way to identify, does a view in Angular is rendered as a subsequent Angular Router navigation request (i.e. internal navigation request)

or

does a view is rendered due to user typing exact URL in his browser bar and view comes up as first view of the app?

Example would be user performing some sort of ordering on page my.page.com/order

and then clicking on this page on button that will invoke router.navigate(['next'])

vs

entering directly my.page.com/order/next to his URL.

Do we have some trusted and production-grade ready solution for this?

Upvotes: 0

Views: 1797

Answers (1)

Naren Murali
Naren Murali

Reputation: 56307

You can listen to router events and then filter out all the navigation end events, then pairwise will emit the last value and the current value, then you store it in variables of a component, or on a service and then solve your issue!

This is from a previous answer, but the gist is on load, you will be getting previousPath as null, while when navigation happens, previous path will contain a value!

ngOnInit() {
    this.router.events
      .pipe(
        filter((x) => x instanceof NavigationEnd), // filter out only the navigation end event
        startWith(null), // set an initial value
        map((x) => x && x.url), // get only the necessary value
        pairwise() // emit both the previous and current value
      )
      .subscribe((event) => {
        console.log('navigation succeeded', event[0], event[1]);
        this.previousPath = event[0];
        this.currentPath = event[1];
      });
  }

forked stackblitz

Upvotes: 2

Related Questions