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

ABHILASHA K.M
  • 146
  • 1
  • 4
  • 16

2 Answers2

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

David
  • 33,444
  • 11
  • 80
  • 118
  • 1
    Its not Working for me!! – ABHILASHA K.M May 04 '20 at 10:02
  • 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? – David May 04 '20 at 10:07
  • 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 – ABHILASHA K.M May 04 '20 at 10:12
  • I need previous URL in oninit function of Parent component – ABHILASHA K.M May 04 '20 at 10:13
  • https://community.wia.io/d/22-access-the-previous-route-in-your-angular-5-app – ABHILASHA K.M May 05 '20 at 07:45
  • https://community.wia.io/d/22-access-the-previous-route-in-your-angular-5-app this works well for me – ABHILASHA K.M May 05 '20 at 07:46
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.

ABHILASHA K.M
  • 146
  • 1
  • 4
  • 16