1

I need Previous URL in OnInit function of Angular TS file.

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

I can get by above Code, but this Repeats multiple times, because I am having lot of child component under Parent. I need any other method, which runs only onces

4
  • save it in sessionStorage or localStorage Commented May 4, 2020 at 8:33
  • @ShlokNangia Its Repeats multiple times Commented May 4, 2020 at 8:37
  • @ShlokNangia If I visited any other component also this code Repeats !!!! Commented May 4, 2020 at 8:44
  • Take look at this answer: stackoverflow.com/a/74887593/6666348 Commented Dec 22, 2022 at 11:06

2 Answers 2

3

You can try using a solution based on this article

@Injectable({
  providedIn: 'root'
})
export class RoutingStateService
{
  private history = [];

  constructor(private router: Router, @Inject(DOCUMENT) private _document: any)
  {
  }

  public recordHistory(): void
  {
    this.router.events
      .pipe(filter(event => event instanceof NavigationEnd))
      .subscribe(({urlAfterRedirects}: NavigationEnd) => {
        this.history = [...this.history, urlAfterRedirects];
      });
  }

  public getHistory(): string[]
  {
    return this.history;
  }

  public getPreviousUrl(): string
  {
    return this.history[this.history.length - 2] || this._document.referrer;
  }
}

Then in your main component's constructor, inject this service and call recordHistory

Sign up to request clarification or add additional context in comments.

6 Comments

Its not Working for me!!
I clarified a bit my answer. If this still does not work, can you elaborate on what your problem is? Any errors? DId you set breakpoints in the code?
I am having Parent Components and Multiple Child components in that. I need previous url from Child to Parent and this url code must not effect any other component. If I added code (Given my question), That will repeats multiple times. By adding your code in my Parent Component I am not getting any URL. Its giving Undefined always
I need previous URL in oninit function of Parent component
|
0

https://community.wia.io/d/22-access-the-previous-route-in-your-angular-5-app

This works well. Better to use Service, Service will executes only required.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.