How to get navigation history?

China☆狼群 提交于 2020-07-08 13:59:24

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!