Suppose I am currently on the page which has the URL /user/:id . Now from this page I navigate to next page :id/posts.
Now Is there a way, so that i can check what is the previous URL, i.e. /user/:id.
Below are my routes
export const routes: Routes = [
{
path: 'user/:id', component: UserProfileComponent
},
{
path: ':id/posts', component: UserPostsComponet
}
];
You can subscribe to route changes and store the current event so you can use it when the next happens
previousUrl: string;
constructor(router: Router) {
router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(e => {
console.log('prev:', this.previousUrl);
this.previousUrl = e.url;
});
}
Maybe all other answers are for angular 2.X.
Now it doesn't work for angular 5.X. I'm working with it.
with only NavigationEnd, you can not get previous url.
because Router works from "NavigationStart", "RoutesRecognized",..., to "NavigationEnd".
You can check with
router.events.forEach((event) => {
console.log(event);
});
But still you can not get previous url even with "NavigationStart".
Now you need to use pairwise.
import 'rxjs/add/operator/filter';
import 'rxjs/add/operator/pairwise';
constructor(private router: Router) {
this.router.events
.filter(e => e instanceof RoutesRecognized)
.pairwise()
.subscribe((event: any[]) => {
console.log(event[0].urlAfterRedirects);
});
}
With pairwise, You can see what url is from and to.
"RoutesRecognized" is the changing step from origin to target url.
so filter it and get previous url from it.
Last but not least,
this code put parent component or higher (ex, app.component.ts)
because this code fire after finish routing.
Create a injectable service:
import { Injectable } from '@angular/core';
import { Router, RouterEvent, NavigationEnd } from '@angular/router';
/** A router wrapper, adding extra functions. */
@Injectable()
export class RouterExtService {
private previousUrl: string = undefined;
private currentUrl: string = undefined;
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;
}
}
Then use it everywhere you need. To store the current variable as soon as possible, it's necessary to use the service in the AppModule.
// AppModule
export class AppModule {
constructor(private routerExtService: RouterExtService){}
//...
}
// Using in SomeComponent
export class SomeComponent implements OnInit {
constructor(private routerExtService: RouterExtService, private location: Location) { }
public back(): void {
this.location.back();
}
//Strange name, but it makes sense. Behind the scenes, we are pushing to history the previous url
public goToPrevious(): void {
let previous = this.routerExtService.getPreviousUrl();
if(previous)
this.routerExtService.router.navigateByUrl(previous);
}
//...
}
Angular 6 updated code for getting previous url as string.
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
});
}
This worked for me in angular 6:
this.router.events
.subscribe((event) => {
if (event instanceof NavigationStart) {
window.localStorage.setItem('previousUrl', this.router.url);
}
});
@GünterZöchbauer also you can save it in localstorage but I not prefer it ) better to save in service and get this value from there
constructor(
private router: Router
) {
this.router.events
.subscribe((event) => {
if (event instanceof NavigationEnd) {
localStorage.setItem('previousUrl', event.url);
}
});
}
I had similar problem when I had wanted to back to previous page. Solution was easier than I could imagine.
<button [routerLink]="['../']">
Back
</button>
And it returns to parent url. I hope it will help someone ;)
来源:https://stackoverflow.com/questions/41038970/how-to-determine-previous-page-url-in-angular