The blog is all about access the previous route
in your Angular app. In a simple way this service work like:
it saves the current
url
, after that, when aNavigationEnd
event fires.it saves that
url
in a variablepreviousUrl
, to be get in your component.
First create a new service PreviousRouteService
. If you're using the Angular CLI
, use the command ng generate service previous-route
and add in your app.module
file.
Your service file will look like below:
import { Injectable } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
@Injectable()
export class PreviousRouteService {
private previousUrl: string;
private currentUrl: string;
constructor(private router: Router) {
this.currentUrl = this.router.url;
router.events.subscribe(event => {
if (event instanceof NavigationEnd) {
this.previousUrl = this.currentUrl;
this.currentUrl = event.url;
};
});
}
public getPreviousUrl() {
return this.previousUrl;
}
}
You can use in your component like below:
To use the previous route url
in your component, first importing the service:
import { PreviousRouteService } from '../services/previous-route.service';
Inject it into the constructor like below:
constructor(
private previousRouteService: PreviousRouteService
) {}
Now you can access the previous url with this.previousRouteService.getPreviousUrl()
.
ngOnInit() {
console.log(this.previousRouteService.getPreviousUrl());
}
Thank you for reading if any suggestion please comment below!!!
Happy Coding!!!
Top comments (6)
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
Thank you bro!
Your solution works very well.
Big thanks, bro. Digging a lot and only your solution works.
As @nosoup4you2 said, this.previousUrl == this.currentUrl. This is because it's being assigned by reference and so if you change the value of currentUrl, the referenced value of previousUrl will change too.
But we don't need to change the solution drastically, it is solved just by changing the assignation line like this:
That way, previousUrl no longer references currentUrl, but a new string instead.
Thanks @slk5611 for your solution.
This does not work.
Doesn't work for me. It returns the current url for some reason.