如何获取导航历史记录? [英] How to get navigation history?

查看:40
本文介绍了如何获取导航历史记录?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现一个菜单,其中包括 Angular 应用程序中最近访问过和最常访问的页面.如何获取导航堆栈?或者我是否需要挂钩 navigationStart 事件并在创建时对其进行编译?

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?

推荐答案

我认为通过简单的方法调用无法获得完整的历史记录,但您可以通过订阅 NavigationEnd 轻松地自行跟踪.

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.

另见:如何在 Angular 中确定上一页 URL?

更新:

您可以将上面的代码与下面的代码结合使用,从您的应用程序开始就订阅您服务中的 NavigationEnd.

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

要在其他地方获取列表,您可以在服务中创建一个 getter.

To get hold of the list in other places you could create a getter in the service.

这篇关于如何获取导航历史记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆