Angular2: How to find out what was previous page url when using angular2 routing

旧街凉风 提交于 2019-11-28 23:35:47
Günter Zöchbauer

The pairwise operator allows to get the current together with the previous value

update  

import 'rxjs/add/operator/pairwise';
import 'rxjs/add/operator/filter';
import { Router, NavigationEnd } from '@angular/router';

export class AppComponent {
    constructor(private router: Router) {
        this.router.events
        .filter(e => e instanceof NavigationEnd)
        .pairwise().subscribe((e) => {
            console.log(e);
        });
    }
}

See also How to detect a route change in Angular?

original (super old)

Inject Router and subscribe to events and store them for later reference

constructor(private _router: Router) {
  this._router.subscribe(route => {
    this.nextRoute ...
    this.prevRoute ...
  });

Yes, I would do it this way:

@Injectable() // do not forget to register this class as a provider
export class PreviousRouteRecorder implements CanDeactivate<any> {
  constructor(private router: Router) {
  }
  canDeactivate(component: any): Observable<boolean> | boolean {
    localStorage.setItem('previousRoute', this.router.url);
    return true;
  }
}

export const ROUTES: Routes = [
  {
    path: 'first',
    component: FirstComponent,
    canDeactivate: [PreviousRouteRecorder]},
  {
    path: 'second',
    component: SecondComponent
  }
];

export class SecondComponent implements OnInit {
  ngOnInit(){
    console.log(localStorage.getItem('previousRoute'));
  }
}

Angular 6 updated code for getting previous url as string.

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


export class AppComponent implements OnInit {

    constructor (
        public router: Router
    ) {
    }

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

You can do this with document.referrer

if(document.referrer !== '/myapp/signup'){
    location.back()
}

You can maybe leverage the OnActivate phase with the routerOnActivate method that gives you access to the previous url and the current one.

routerOnActivate(next: ComponentInstruction, prev: ComponentInstruction) {
  console.log(`Finished navigating from "${prev ? prev.urlPath : 'null'}" to "${next.urlPath}"`);
}

The implementation with the pairwise will not work if the user doesn't trigger navigation event at least two times and may cause a small bug.

page 1 -> page 2 ---> navigation event triggered, but event Observable has only 1 value and thus pairwise does not emit ---> User cannot go back to page 1

page 2 -> page 3 --> event Observable now has 2 elements and pairwise emits

I wonder if there is a workaround?

Soumya K

You can set the previous url using a auth guard and set the previous url in any were of the application.

canActivate(route: ActivatedRouteSnapshot, snapshot: RouterStateSnapshot) {
                this.commonService.prevRouter = this.router.url;
}
import {Location} from '@angular/common';

 private currentLocation;
 constructor(private location: Location){
    this.currentLocation = this.location.path();  
   }

ngAfterViewInit() {
 let instance = this;
 this.router.parent.subscribe(() => {            
        if (instance.currentLocation != instance.location.path()) {
             console.log("previous -> "+instance.currentLocation+" != next -> "+instance.location.path());             
        }else{
            console.log("previous -> "+instance.currentLocation+" == next -> "+instance.location.path());
        }
    });
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!