15

I am developing an angular2 app and I use router. I am in a page /myapp/signup. after signup I navigate the use to /myapp/login. /myapp/login can also be navigated from my home page which is /myapp. So now, when the user users /myapp/login I go back. This can be done by using location.back(). But I dont want to go back when the user is coming from /myapp/signup. So I should check if the user is coming from /myapp/signup and if so, I want to direct it to somewhere else. How can I know the previous url so that I direct the user to a specific state based on that ?

1

8 Answers 8

25

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 ... }); 
Sign up to request clarification or add additional context in comments.

13 Comments

Thanks for the hint! Updated. See also stackoverflow.com/questions/33520043/…
This approach is helping me to re-write a non-standard breadcrumb. Very handy!
I had to go to previous page after certain operation. This solved the problem with minimal code. Thanks!
This doesn't work if you need the previousUrl on a route component that just loaded, this needs two navigation events while in the same component. Does the Router/ActivatedRoute not store the previous url anywhere?
Ps. I'm now using a service for this, which I think is a good practice. Moreover, what is the type of e when I use the update example above? Currently hacking it like so: const prev = <NavigationEnd>e[0] const cur = <NavigationEnd>e[1] console.log('Previous url' + prev.url) console.log('Previous url' + cur.url)
|
1

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')); } } 

Comments

1

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 }); } 

Comments

0

You can do this with document.referrer

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

4 Comments

Not working when I test it. document.referer returns nothing in all the cases. Maybe it doesnt behave the this way when in angular2 ?
Im using angular2 router.navigate to navigate to the new state!
Aha, so you are not coming from another url? The url isn't changing?
I am coming from another URL. I am in localhost/myapp/signup and I navigate to /myapp/login USING angular Router.navigate method. For some reason document referer is always empty regardless of where I am coming from to /myapp/login. I m thinking angular should has this functionality to know which url I am coming from.
0

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}"`); } 

2 Comments

this worked well for me, cheers, just need to make sure ComponentInstruction is imported :) import {Router, ComponentInstruction} from 'angular2/router';
This is outdated.
0

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?

4 Comments

Read the help, don't post questions and comments as answers. If you want to comment other answer and you can't do it, try to level up first.
@PhoneixS Maybe you should read the help to understand that not everyone can post a comment. Such annoyance receiving notifications from you for nothing
I was only reporting the rules of this site. I have also started from 1 reputation without comments so I know how it is and this does not exempt from complying with the rules.
I am having the same problem, the pairwise operator does not work as expected as commented by @Hou. Is there a solution to this?
0

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; } 

Comments

-1
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()); } }); } 

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.