Sayeed Mohammad
Sayeed Mohammad

Reputation: 11

How to get the previous page URL in angular 10

How to get the previous page url in angular 10? I am trying to use the filter, pairwise and router RoutesRecognized originally mentioned in the below post

How to determine previous page URL in Angular?

First time it does not return any value and second onward it return and third time it returns the value 2 times and increment next time.

How to get the exact value from first time and should console only one time evrytime return in this page?

import { Component, OnInit } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';
import { filter, pairwise } from 'rxjs/operators';

@Component({
  selector: 'app-a',
  templateUrl: './a.component.html',
  styleUrls: ['./a.component.css']
})
export class AComponent implements OnInit {

  constructor(
    private router: Router
  ) { }

  ngOnInit(): void {
    this.router.events
      .pipe(filter((e: any) => e instanceof RoutesRecognized),
        pairwise()
      ).subscribe((e: any) => {
        console.log(e[0].urlAfterRedirects); // previous url
    });
  }
}

Upvotes: 1

Views: 1422

Answers (1)

A Praveen Kumar
A Praveen Kumar

Reputation: 303

You can use event instanceof NavigationEnd and create a service to persist the currentUrl and assign it back to previous url on any router NavigationEnd event.

I have created a Stackblitz with a quick demo of usecase: https://stackblitz.com/edit/angular-xw94et?file=src/app/app.component.html

Upvotes: 1

Related Questions