问题
I am trying to implement a menu including the most recently visited and most commonly visited pages within the Angular app. How can I get the navigation stack? Or do I need to hook the navigationStart
event and compile it as it is created?
回答1:
I don't think it is possible to get the full history with a simple method call, but you can track this easily yourself by subscribing to the NavigationEnd.
previousUrl: string;
constructor(router: Router) {
router.events
.filter(event => event instanceof NavigationEnd)
.subscribe(e => {
console.log('prev:', this.previousUrl);
this.previousUrl = e.url;
});
}
In this sample it saves only the previous route, but you could store in an array to save all the previously visited routes.
See also: How to determine previous page URL in Angular?
Update:
You can use the above code in combination with the code below to subscribe to the NavigationEnd in your service from the start of your application.
export class AppModule {
constructor(navigationEndService: NavigationEndService) {
navigationEndService.init();
}
To get hold of the list in other places you could create a getter in the service.
来源:https://stackoverflow.com/questions/54999052/how-to-get-navigation-history