DEV Community

Discussion on: How to access the previous route in your Angular app

Collapse
 
nosoup4you2 profile image
NoSoup4you2

if you read the code it returns the this.previousUrl = this.currentUrl. I think its great if people spent time and contribute to community, but they should make sure what they post its valid.

Here is the revised code which works at least for me

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

@Injectable()
export class PreviousRouteService {

 private previousUrl: string;

 constructor(private router: Router) {

this.router.events
  .pipe(filter((evt: any) => evt instanceof RoutesRecognized), pairwise())
  .subscribe((events: RoutesRecognized[]) => {
    this.previousUrl = events[0].urlAfterRedirects;
    console.log('previous url', this.previousUrl);
  });
 }
 public getPreviousUrl() {
  return this.previousUrl;
 }
 } 
Enter fullscreen mode Exit fullscreen mode
Collapse
 
kif profile image
Kirill • Edited

Big thanks, bro. Digging a lot and only your solution works.

Collapse
 
adriansilvadonascimento profile image
Adrian Silva

Thank you bro!
Your solution works very well.