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?
            Asked
            
        
        
            Active
            
        
            Viewed 1.0k times
        
    8
            
            
        - 
                    What is the scope? Do you want to track most popular pages for the current user? all users? all tabs/windows? – umutesen Mar 05 '19 at 09:28
- 
                    At the moment Angular doesn't have built-in possibility to get all navigation history. You need to use navigation events to store navigation history for further needs. – taras-d Mar 05 '19 at 10:00
- 
                    you can store all visited route. your question answers is [this link](https://stackoverflow.com/questions/49771781/navigate-to-last-visited-child-route-when-entering-parent-route-angular-5) – mosi98 Mar 05 '19 at 10:22
1 Answers
3
            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.
 
    
    
        Mikey123
        
- 1,201
- 2
- 12
- 23
- 
                    Question is not about only previous URL, but navigation history or recently visited pages. – Ushma Joshi Mar 05 '19 at 09:22
- 
                    You can't see the full history because Angular uses the browser history mechanism, which does not expose the details of the history. – Mikey123 Mar 05 '19 at 11:39
- 
                    It seems like this is the most likely approach. Where would you hook on to the navigationEnd event so that it caught every navigation event - and then how do you reference it to get the value out of the array? – statler Mar 06 '19 at 07:40
- 
                    You can do the above in a service class for example. You could initialize the route event listener in your app.module file so that your service is subscribed to the NavigationEnd event.I updated the answer above. – Mikey123 Mar 06 '19 at 08:41
 
    