问题描述
我正在尝试实现一个菜单,其中包含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轻松地跟踪此历史记录./p>
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();
}
要在其他地方获得列表,您可以在服务中创建一个吸气剂.
To get hold of the list in other places you could create a getter in the service.
这篇关于如何获取导航历史记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!